你为什么要?
Calculator<std::string> a;
std::cout << a.add("Hello", " world") << std::endl;
此代码输出“Hello world”。它不是最优的(std::string
成员函数中的add
参数是按值取值的),但它不需要专门化工作。
编辑好的,你想要专业化,但你不能只专注于add
成员函数,因为该函数本身不是模板。您可以专注全班:
template<>
class Calculator<std::string>
{
public :
Calculator() {}
~Calculator() {}
std::string add(const std::string &a, const std::string &b)
{
// Do std::string specific stuff
return a + b ;
}
};
,或使add
成员函数模板,并专注它:
class Calculator
{
public :
Calculator() {}
~Calculator() {}
template<class T>
T add(T a, T b)
{
return a + b;
}
};
template<>
std::string Calculator::add<std::string>(std::string a, std::string b)
{
// Do std::string specific stuff
return a + b ;
}
用第二种方案,那么单个Calculator
实例将能够添加int
, std::string
或任何你需要的东西(因为它的add
功能是模板,而不是Calculator
类本身)。
@silico,@icecrime,通过使用STL,我可以做到这一点;但我想用模板专业化 – 2010-11-22 10:36:57
@Sujay Ghosh:为什么需要模板专业化?使用'std :: string'远不如创建'Calculator'的新专门化。 –
2010-11-22 10:38:23
我认为第二个解决方案是一个更好的设计。如果有一天我想添加一个自定义类,而不是任何PODS,这将解决我的问题。 – 2010-11-26 07:00:12