如何专门化模板子类?

时间:2015-04-09 23:27:29

标签: c++ templates template-specialization

我正在尝试在另一个类中专门化一个模板类,但编译器不会让我。代码在类Foo之外工作,但不在内部,我希望struct Bla对Foo类是私有的。

class Foo {
   template<typename ... Ts> struct Bla; 
   template<> struct Bla<> { static constexpr int x = 1; };
};

error: explicit specialization in non-namespace scope 'class Foo'

2 个答案:

答案 0 :(得分:4)

你根本做不到。错误很好地总结了它。类模板只能专门用于命名空间范围。 class Foo不是命名空间。

您可以在类外部执行此操作,根据标准[temp.class.spec]中的此示例:

  

可以在其中的任何命名空间范围内声明或重新声明类模板部分特化   定义可以定义(14.5.1和14.5.2)。 [例如:

 template<class T> struct A {  
     struct C {
         template<class T2> struct B { };
     };
 };

 // partial specialization of A<T>::C::B<T2>
 template<class T> template<class T2>
   struct A<T>::C::B<T2*> { };

A<short>::C::B<int*> absip; // uses partial specialization
     

-end example]

答案 1 :(得分:3)

你不能在课堂上专攻,使用:

class Foo {
public: // so we can test it easily
   template<typename ... Ts> struct Bla; 
};

// specialize it outside the class
template<> class Foo::Bla<> { static constexpr int x = 1; }; 

int main()
{
    std::cout << Foo::Bla<>::x;
}