Search code examples
c++templatesmember-functionsexplicit-specialization

class template special member function explicit specialization


In c++ iso 2003/2011 [temp.expl.spec]/4 written that

A member function, a member class or a static data member of a class template may be explicitly specialized for a class specialization that is implicitly instantiated; in this case, the definition of the class template shall be in scope at the point of declaration of the explicit specialization for the member of the class template. If such an explicit specialization for the member of a class template names an implicitly-declared special member function (clause 12), the program is ill-formed.

So as I understand special functions to be allowed to be specialized should be defined before explicit specialization.

template <typename T>
class A
{
public:
    A()
    { /* some definition */}
};

template <>
A<int>::A()
{ /*explicit specialization def body*/} // this is OK

but

template <typename T>
class B
{};

template <>
B<int>::B()
{ /*explicit specializationdef body */} // this is forbidden by ISO c++
                                        // and when compiling with VS2013 gives compile error
                                        // cannot define a compiler-generated special member
                                        // function (must be declared in the class first)

What is the reason to have such restrictions?


Solution

  • It's consistent with the way definitions of member function normally work. You only can define functions you have declared first. For example this won't compile:

    struct B {
    };
    
    B::B() {
    }
    

    The constructor is implicitly declared, and so can't be explicitly defined.

    The paragraph you quoted says that this works the same for template specializations.