Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specialize a template sub-class?

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'
like image 570
Goswin von Brederlow Avatar asked Apr 09 '15 23:04

Goswin von Brederlow


2 Answers

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 ]

like image 54
Barry Avatar answered Oct 21 '22 07:10

Barry


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;
}
like image 25
vsoftco Avatar answered Oct 21 '22 07:10

vsoftco