c++ - 专门化模板类的模板成员函数?

标签 c++ templates template-specialization

我有一个模板类,它有一个需要专门化的模板成员函数,如:

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/

相关文章:

c++ - 正确发送消息 UART

c++ - 使用声明引入的枚举

c++ - std::map 的所有迭代器的模板特化

c++ - 在这种特殊情况下,为什么不需要将 std::hash() 的特化注入(inject)到 std namespace 中?

c++ - 如何在其他模板类中专门化模板类?

c++ - 作者在 GotW #53 中想表达什么?

c++ - 将包含字符串数组和整数数组的结构传递给 C++ DLL

c++ - 这个模板定义有什么问题?

c++ - 如果类型来自 std,是否可以创建一个特征来回答?

带有变量和类型的 C++03 宏定义?