用于特化模板类中的模板函数的 C++ 语法是什么?例如,考虑我有以下两个类及其用法。我希望能够为不同类型提供方法 X::getAThing() 的专门实现。例如:int、std::string、任意指针或类等
template <class c1> class X {
public:
template<typename returnT> returnT getAThing(std::string param);
static std::string getName();
private:
c1 theData;
};
// This works ok...
template <class c1> std::string X<c1>::getName() {
return c1::getName();
}
// This blows up with the error:
// error: prototype for 'int X<c1>::getAThing(std::string)' does not match any in class 'X<c1>'
template <class c1> template <typename returnT> int X<c1>::getAThing(std::string param) {
return getIntThing(param); // Some function that crunches on param and returns an int.
}
// More specialized definitions of getAThing() for other types/classes go here...
class Y {
public:
static std::string getName() { return "Y"; }
};
int main(int argc, char* argv[])
{
X<Y> tester;
int anIntThing = tester.getAThing<int>(std::string("param"));
cout << "Name: " << tester.getName() << endl;
cout << "An int thing: " << anIntThing << endl;
}
至少一个小时以来,我一直在尝试猜测特化的正确语法,但无法弄清楚任何可以编译的东西。任何帮助将不胜感激!
最佳答案
AFAIK(标准专家可以纠正我),如果不专门化类本身,就无法专门化类模板的模板化函数...
即以下我认为会起作用:
template <> template <> int X<Y>::getAThing<int>(std::string param) {
return getIntThing(param); // Some function that crunches on param and returns an int.
}
关于模板类中模板函数的 C++ 特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4994775/