c++ - 模板类特化的模板方法

标签 c++ linux templates g++

这是我的代码:

template<typename T1, typename T2> class MyClass
{
public:
    template<int num> static int DoSomething();
};

template<typename T1, typename T2> template<int num> int MyClass<T1, T2>::DoSomething()
{
    cout << "This is the common method" << endl;
    cout << "sizeof(T1) = " << sizeof(T1) << endl;
    cout << "sizeof(T2) = " << sizeof(T2) << endl;
    return num;
}

效果很好。但是当我尝试添加这个时

template<typename T1, typename T2> template<> int MyClass<T1, T2>::DoSomething<0>()
{
    cout << "This is ZERO!!!" << endl;
    cout << "sizeof(T1) = " << sizeof(T1) << endl;
    cout << "sizeof(T2) = " << sizeof(T2) << endl;
    return num;
}

我收到编译器错误: «>» 标记前无效的显式特化 «int MyClass::DoSomething()» 的模板 ID «DoSomething<0>» 不匹配任何模板声明

我使用 g++ 4.6.1 我该怎么办?

最佳答案

不幸的是,如果不特化外部模板,就无法特化作为类模板成员的模板:

C++11 14.7.3/16: In an explicit specialization declaration for a member of a class template or a member template that appears in namespace scope, the member template and some of its enclosing class templates may remain unspecialized, except that the declaration shall not explicitly specialize a class member template if its enclosing class templates are not explicitly specialized as well.

我认为您最好的选择是将额外参数添加到 MyClass,然后对其进行部分特化。

关于c++ - 模板类特化的模板方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9276389/

相关文章:

c++ - 有符号整数类型的大小是否可以不同于 C/C++ 中对应的无符号整数类型的大小?

c++ - while循环和bool使程序结束

c++ - 我们可以只为某些数据类型定义模板函数吗?

c++ - std::vector 作为 MPI 非阻塞函数的输入缓冲区

c - 忽略我不想复制到文本文件中的字符串

linux - 服务套接字会在核心转储之前或之后关闭吗?

python - Raspberry Pi 和 PiFace Digital 的中断

c++在不知道扩展类的情况下调用存储在基类变量中的扩展类的构造函数

c++ - C++ 模板中具有参数化类型的结构如何初始化?

c++ - 请帮助使用 MFC CMap(或 std::map)