How to specialize a subclass of a class?

I am trying to specialize a template class inside another class, but the compiler does not allow me. The code works outside the Foo class, but not inside, and I want the Bla structure to be private to the Foo class.

class Foo { template<typename ... Ts> struct Bla; template<> struct Bla<> { static constexpr int x = 1; }; }; error: explicit specialization in non-namespace scope 'class Foo' 
+5
source share
2 answers

You cannot specialize inside a class, use:

 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; } 
+3
source

You just can't do it. The error summarizes it well. Class templates can only be specialized in the field of namespace. class Foo not a namespace.

You can make this external to the class, as in this example, from the standard [temp.class.spec]:

Partial specialization of a template template can be declared or redefined in any area of ​​the namespace in which its definition can be defined (14.5.1 and 14.5.2). [Example:

  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]

+4
source

All Articles