简体   繁体   English

在课堂上专门研究模板化函数

[英]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): 这将导致此编译器错误(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. 据我了解,不可能对功能模板进行部分专业化,但这是完全专业化。

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM