Andrew Tomazos
Andrew Tomazos

Reputation: 68698

Out-of-class definition of function of specialized inner class template?

Please consider the following ill-formed program:

struct S {
    template<class T> struct J { };
};

template<>
struct S::J<void> {
    void f();
};

template<>
void S::J<void>::f() {} // ERROR

$ clang++ -std=c++11 test.cpp 
no function template matches function template specialization 'f'

$ g++ -std=c++11 test.cpp
template-id ‘f<>’ for ‘void S::J<void>::f()’ does not match any template declaration

Why doesn't the definition of f compile? How do I define the function f correctly in the above?

Upvotes: 5

Views: 261

Answers (1)

Barry
Barry

Reputation: 303287

The clang error is very helpful here:

no function template matches function template specialization 'f'
// ^^^^^^^^^^^^^^^^^

The syntax you're using is for a function template. But f isn't a function template, it's just a function. To define it, we don't need the template keyword:

void S::J<void>::f() {}

At this point, S::J<void> is just another class, so this is no different than your standard:

void Class::method() { }

You'd only need template if you were defining a member function of a template, for instance:

template <typename T>
void S::J<T>::g() { }

or a member function template:

template <typename T>
void S::J<void>::h<T>() { }

Upvotes: 8

Related Questions