如何在c ++类中使用模板专业化,以及为什么不编译?

Tib*_*ibi 13 c++ templates class template-specialization

我正在研究一个XmlWriter类,我希望能够以大多数标准数据格式(字符串,整数,浮点数等)输出属性或文本.为此,我使用的是文件流.

对于bool数据类型,我想指定模板的特化,以便输出truefalse不是10.

但是,以下代码似乎没有编译:

class XmlWriter {

private: /* ... */

public: /* ... */

    template <typename T>
    void writeText(T text)  {
        /* ... */
    }

    template <>  // <-- error: explicit specialization in non-namespace scope 'class Strategy::IO::XmlWriter'
    void writeText<bool> (bool text) {  // <-- error: template-id 'writeText<>' in declaration of primary template
        /* ... */
    }

    template <typename T> 
    void writeAttribute(std::string key, T value) { // <-- error: too many template-parameter-lists
        /* ... */
    }

    template <>  // <-- error: explicit specialization in non-namespace scope 'class Strategy::IO::XmlWriter'
    void writeAttribute<bool> (std::string key, bool value) { // <-- error: variable or field 'writeAttribute' declared void; expected ';' before '<' token
        /* ... */
    }
}; // <-- expected ';' before '}' token
Run Code Online (Sandbox Code Playgroud)

我不明白,为什么所有这些错误,因为我使用了互联网上各种网站上提供的正确语法?

我正在使用Cygwin GCC.

Rob*_*obᵩ 13

非命名空间范围'class Strategy :: IO :: XmlWriter'中的显式特化

尝试将专业化移动到命名空间范围?

class XmlWriter {

private: /* ... */

public: /* ... */

    template <typename T>
    void writeText(T text)  {
    }


    template <typename T>
    void writeAttribute(std::string key, T value) {
    }


}; 

template <>
void XmlWriter::writeText<bool> (bool text) {
}

template <>
void XmlWriter::writeAttribute<bool> (std::string key, bool value) {
}
Run Code Online (Sandbox Code Playgroud)

  • 这似乎没有编译,它给了我已经定义的错误。我不确定如何在多文件项目中正确定义它,我尝试了许多组合,但似乎都没有用。 (2认同)
  • @Tibi:我很确定*编译*,如果包含在不同的翻译单元中,它可能无法*链接*。您只需将专业化标记为“内联”即可避免 ODR 违规。作为旁注,您可能应该“重载”(即定义一个不同的“void writeText(bool)”非模板化成员函数,而不是专门化) (2认同)

hmj*_*mjd 6

而不是专业化你可以只是重载writeText()writeAttribute():

class XmlWriter {

private: /* ... */

public: /* ... */

    template <typename T>
    void writeText(T text)  {}

    void writeText(bool text) {}

    template <typename T> 
    void writeAttribute(std::string key, T value) {}

    void writeAttribute(std::string key, bool value) {}
};
Run Code Online (Sandbox Code Playgroud)

用g ++ v4.6.1编译.