如何专门化模板子类?

Gos*_*low 5 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'
Run Code Online (Sandbox Code Playgroud)

vso*_*tco 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;
}
Run Code Online (Sandbox Code Playgroud)