c++visual-studiotemplatesnested

Move method definition for template nested class outside declaration


Is it possible to move method definition outside declaration?

template <typename T1>
class A
{
  template <bool T2>
  class B;

  template<>
  class B<true>
  {
    void f() { /* Do smg */ }
  }
  class B<false>
  {
    void f() { /* Do smg else */ }
  }
}

If I try to define f() outside class declaration, like this

template <typename T1>
template <>
void A<T1>::B<true>::f() { /* Do smg */ }

compiler gives error C3855: template parameter T2 is incompatible with the declaration.


Solution

  • You cannot explicitly specialize a class member template of a non-specialized class template, from [temp.expl.spec]:

    In an explicit specialization declaration for a member of a class template or a member template that appears in namespace scope, the member template and some of its enclosing class templates may remain unspecialized, except that the declaration shall not explicitly specialize a class member template if its enclosing class templates are not explicitly specialized as well.

    Even the explicit specialiation of B inside of the definition of A is ill-formed. If you need to do such a thing, I would simply not use a member class template for B.