3

给定一个带有单个参数的模板类,我可以为特定的专业定义一个实现:

template<int N>
struct Foo {
    Foo( );
};

Foo<2>::Foo( ) { //works (on MS Visual 2012, even though it's not the most correct form)
}

对于多参数模板,是否可以定义部分专业化的实现?

template <class X, int N>
struct Bar {
    Bar( );
};

template <class X>
Bar<X,2>::Bar( ) { //error
}
4

2 回答 2

4

对于部分特化,您需要先定义类模板本身的特化,然后才能定义其成员:

template <class X, int N>
struct Bar {
    Bar();
};

template<class X>
struct Bar<X,2> {
    Bar();
};

template <class X>
Bar<X,2>::Bar( ) { }

您所说的第一个有效的正确形式是:

template<int N>
struct Foo {
    Foo( );
};

template<>
Foo<2>::Foo( ) { //works
}
于 2013-08-15T16:10:25.697 回答
0

在专门化其成员之前,您需要专门化类本身。所以

template <class X, int N>
struct Bar {
    Bar();
};
template<class X>
struct Bar<X,2> {
    Bar();
};
template<class X>
Bar<X,2>::Bar( ) 
{ //error gone
}

您可以进一步将您的构造函数专门化为:

template<>
Bar<int,2>::Bar( ) 
{ //error gone
}
于 2013-08-15T16:18:45.363 回答