简体   繁体   English

C ++:模板模板类的部分特化

[英]C++: partial specialization of template template classes

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() ? 为什么我不能部分专门化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? 我有另一个问题:如果我只想为A = int,B = Hoo定义foo2()而不是任何其他组合,我该怎么做?

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: 类模板的成员函数是自动函数模板,它们可能确实是专用的,但只是完全:

template <>
void Foo<int, Goo>::foo1() { }  // OK

You can partially specialise the entire class and then define it anew: 您可以部分地专门化整个 ,然后重新定义它:

template <typename A>
struct Foo<A, Goo>
{
  // ...
};

(See 14.7.3 for details.) (详见14.7.3)

The template still has two parameters, and you must write something like this: 模板仍然有两个参数,你必须写这样的东西:

template <typename A, template <typename> class B>
void Foo<A,B>::foo1() { cout << "foo1" << endl;}

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). 无论B是什么(默认或其他),此代码都适用。 If you then wish to specify different behaviour for a particular B, then you do specialization of the class, not just of a method. 如果您希望为特定B指定不同的行为, 那么您将对该类进行专门化,而不仅仅是对方法的专门化。

( Heavily edited ) 重编辑

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM