模板类专门化的模板方法 [英] Template method of template class specialization

查看:289
本文介绍了模板类专门化的模板方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码:

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;
}

我得到编译器错误:
token
template-id«DoSomething< 0>»对于«int MyClass :: DoSomething()»不匹配任何模板声明

I get compiller errors: invalid explicit specialization before «>» token template-id «DoSomething<0>» for «int MyClass::DoSomething()» does not match any template declaration

我使用g ++ 4.6。 1
我该怎么办?

I use g++ 4.6.1 What should I do?

推荐答案

不幸的是,你不能专门化一个类的成员模板模板,没有专门的外部模板:

Unfortunately, you can't specialise a template that's a member of a class template, without specialising the outer template:


C ++ 11 14.7.3 / 16:类模板或出现在命名空间范围中的成员模板,成员模板及其某些封闭类模板可能保持未专门化,除了声明不应明确专门化类成员模板,如果其类封装类模板未明确专用

/ code>,然后部分专门化。

I think your best option is to add the extra parameter to MyClass, and then partially specialise that.

这篇关于模板类专门化的模板方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆