我有一个模板类,它有一个需要专门化的模板成员函数,如:
template <typename T>
class X
{
public:
template <typename U>
void Y() {}
template <>
void Y<int>() {}
};
虽然 VC 正确处理了这个问题,但显然这不是标准的,GCC 提示:explicit specialization in non-namespace scope 'class X<T>'
我试过:
template <typename T>
class X
{
public:
template <typename U>
void Y() {}
};
template <typename T>
// Also tried `template<>` here
void X<T>::Y<int>() {}
但这导致 VC 和 GCC 都提示。
正确的做法是什么?
最佳答案
很常见的问题。解决它的一种方法是通过重载
template <typename T>
struct type2type { typedef T type; };
template <typename T>
class X
{
public:
template <typename U>
void Y() { Y(type2type<U>()); }
private:
template<typename U>
void Y(type2type<U>) { }
void Y(type2type<int>) { }
};
关于c++ - 专门化模板类的模板成员函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3040201/