模板类中模板函数的 C++ 特化

标签 c++ templates syntax template-specialization

用于特化模板类中的模板函数的 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/

相关文章:

c++ - boost condition_variable 销毁断言

c++ - 独立源文件中的 SFINAE 模板特化

部分模板的 C++ typedef

c - 如何声明一个外部字符指针?

c++ - std::strtod() 中的十进制错误与 Visual Studio 2015,64 位

c++ - CreatePen 不会造成内存泄漏吗?

c++ - Boost::Test——Main() 的生成?

c++ - wchar_t 的模板特化

objective-c - 如何使用 .notation 在 Objective-C 中设置数组的值?

c# - 了解 linq 语法