uj2*_*uj2 5 c++ templates template-specialization
我有一个模板类,它具有需要专门化的模板成员函数,如:
template <typename T>
class X
{
public:
template <typename U>
void Y() {}
template <>
void Y<int>() {}
};
Run Code Online (Sandbox Code Playgroud)
Altough 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>() {}
Run Code Online (Sandbox Code Playgroud)
但这导致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>) { }
};
Run Code Online (Sandbox Code Playgroud)