Why does this code give the error, "template specialization requires 'template<>'"?

user541686 picture user541686 · Mar 30, 2013 · Viewed 9.5k times · Source

When I try to compile this with Clang

template<class T>
struct Field
{
    char const *name;
    Field(char const *name) : name(name) { }
};

template<class Derived>
class CRTP { static Field<Derived> const _field; };

class Class : public CRTP<Class> { };
Field<Class>   const CRTP<Class>::_field("blah");

int main() { }

I get

error: template specialization requires 'template<>'
Field<Class>   const CRTP<Class>::_field("blah");
                     ~~~~~~~~~~~  ^

I don't understand the error at all. What is wrong with my definition of _field and how do I fix it?

(Note that the arguments to _field are not necessarily the same for all subclasses.)

Answer

dyp picture dyp · Mar 30, 2013

For the compiler to identify this as a template specialization (e.g. to be able to check the syntax), you need the template keyword:

template<>
Field<Class> const CRTP<Class>::_field("blah");

Its brackets are empty as all template parameters are specialized, but you cannot just leave it away.