C++:模板模板类的部分特化
以下代码:
using namespace std;
template <typename X>
class Goo {};
template <typename X>
class Hoo {};
template <class A, template <typename> class B = Goo >
struct Foo {
B<A> data;
void foo1();
void foo2();
};
template <typename A>
void Foo<A>::foo1() { cout << "foo1 for Goo" << endl;}
int main() {
Foo<int> a;
a.foo1();
}
给我一个编译器错误:
test.cc:18: error: invalid use of incomplete type 'struct Foo<A, Goo>'
test.cc:11: error: declaration of 'struct Foo<A, Goo>'
为什么我不能部分特化 foo1() ?如果这不是办法,我该怎么做?
我还有另一个问题:如果我只想为 A=int, B=Hoo 定义 foo2() 怎么办 而不是任何其他组合,我该怎么做?
The following code:
using namespace std;
template <typename X>
class Goo {};
template <typename X>
class Hoo {};
template <class A, template <typename> class B = Goo >
struct Foo {
B<A> data;
void foo1();
void foo2();
};
template <typename A>
void Foo<A>::foo1() { cout << "foo1 for Goo" << endl;}
int main() {
Foo<int> a;
a.foo1();
}
gives me a compiler error:
test.cc:18: error: invalid use of incomplete type 'struct Foo<A, Goo>'
test.cc:11: error: declaration of 'struct Foo<A, Goo>'
Why can't I partially specialize foo1() ? If this is not the way, how do I do this?
I have another question: what if I want foo2() to be defined only for A=int, B=Hoo
and not for any other combination, how do I do that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
函数模板只能完全专用,而不是部分专用。
类模板的成员函数自动成为函数模板,它们确实可能是特化的,但只是完全特化:
您可以部分特化整个类,然后重新定义它:(
有关详细信息,请参阅14.7.3。)
Function templates may only be fully specialized, not partially.
Member functions of class templates are automatically function templates, and they may indeed be specialized, but only fully:
You can partially specialise the entire class and then define it anew:
(See 14.7.3 for details.)
模板还是有两个参数,必须这样写:
默认已经指定了,只需要指定一次。从那时起,它就像任何其他双参数模板一样。无论 B 是什么(默认或其他),此代码都将适用。如果您希望为特定的 B 指定不同的行为,那么您需要对类进行专门化,而不仅仅是方法。
(大量编辑)
The template still has two parameters, and you must write something like this:
The default has been specified, and only needs to be specified once. From then on, it's just like any other two-parameter template. This code will apply no matter what B is (defaulted or otherwise). If you then wish to specify different behaviour for a particular B, then you do specialization of the class, not just of a method.
(Heavily edited)