C++模板;部分特化实现

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

1
请注意,显而易见的含义是,在部分特化中常见的任何代码都需要复制(或移至滥用继承的基类)。类型的特化会生成无关的类型——这与成员函数的特化不同。 - David Rodríguez - dribeas
@DavidRodríguez-dribeas 如果我没记错的话,这是无法避免的,对吗? - jrok
正确,不是批评答案,只是说明你能做到的最好方式与他想要完成的方式有所不同。 - David Rodríguez - dribeas
谢谢...我就怕这样(必须使用继承...)。实际上,我只是用以下代码:if (N == 2) { - gerardw

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
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接