I'm trying to specialize a template class inside another class but the compiler won't let me. The code works outside of class Foo but not inside and I want struct Bla to be private to class 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'
You simply cannot do that. The error sums it up nicely. Class templates can only be specialized in namespace scope. class Foo
is not a namespace.
You can do it external to the class, as per this example from the standard [temp.class.spec]:
A class template partial specialization may be declared or redeclared in any namespace scope in which its definition may 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 ]
You cannot specialize inside the 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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With