现在的位置: 首页 > 综合 > 正文

成员模板特化的概念_隶属相同的类

2014年02月05日 ⁄ 综合 ⁄ 共 1430字 ⁄ 字号 评论关闭
成员模板特化
1。需是一个特化版本类的成员

template<class T1>
class A
{
public:
    template<class T2>
    static void fun();
    template<>
    static void fun<int>();
};

template<class T1> template<class T2>
void A<T1>::fun(){cout << "okokok" << endl;}

template<class T1> template<>
void A<T1>::fun<int>(){cout << "int_okokok" << endl;} //illegal use of explicit template arguments
                                                                                                    //an explicit specialization of a template
                                                                                                    //member must be a member of an explicit                                                                                                                     //specialization

int main()
{
    A<int>::fun<int>();
    A<int>::fun<bool>();
    return 0;
}

2。实现在类内时的可以

template<class T1>
class A
{
public:
    template<class T2>
    static void fun();
    template<>
    static void fun<int>();

    template<>
    static void fun<int>(){cout << "int_okokok" << endl;}
};

template<class T1> template<class T2>
void A<T1>::fun(){cout << "okokok" << endl;}

int main()
{
    A<int>::fun<int>();
    A<int>::fun<bool>();
    return 0;
}

综合上述可以见,
1。特化版本需在通用版本之后才能定义(函数模板,类模板)
2。模板成员的特化,需隶属相同的个类(实例化的时候)才行,写在类内能使得特化版本与通用版本同时属于A<T>,写在类的外则可能通用版本A<T1>的,特化版本A<T2>的,即使T1=T2,也是两个范围的值相同,而并非相同范围的概念的
3。C++ template 199页说明template<>不能跟在一个template parameter list之后,写在类内这样避免

devcpp给的错误提示:explicit specialization in non-namespace scope `class <unnamed>::A'
bcb6给的错误提示Cannot explicitly specialize a member of a generic template class
VS2005、intel9.1编译通过

如果A不是模板类,devcpp仍然编译出错,bcb6可以编译通过

抱歉!评论已关闭.