Nidhoegger
Nidhoegger

Reputation: 3

Specialize templated function in class

I am currently getting into templates and I am trying to fully specialize a class function here in my class (only relevant code):

class item_t
{
public:
    template<class T>
    void set(const std::string &key, const T &value);
    template<>
    void set(const std::string &key, const std::string &value);
};

which will result in this compiler error (gcc 6.3.0):

Fehler: explicit specialization in non-namespace scope ‘class base::data::item_t’
  template<>
           ^

What am I missing here? From what I understood, it is not possible to partially specialize a function template, but this is a full specialization.

Upvotes: 0

Views: 37

Answers (1)

Vittorio Romeo
Vittorio Romeo

Reputation: 93384

You cannot explicitly specialize a template member function inside the class definition. You have to do it outside (in a namespace scope):

class item_t
{
public:
    template<class T>
    void set(const std::string &key, const T &value);

};

template<>
void item_t::set<std::string>(const std::string &key, const std::string &value)
{
}

In your particular use case, you don't even need a specialization - an overload will work just fine:

template<class T>
void set(const std::string &key, const T &value);

void set(const std::string &key, const std::string &value);

Upvotes: 1

Related Questions