Tib*_*ibi 13 c++ templates class template-specialization
我正在研究一个XmlWriter类,我希望能够以大多数标准数据格式(字符串,整数,浮点数等)输出属性或文本.为此,我使用的是文件流.
对于bool数据类型,我想指定模板的特化,以便输出true而false不是1和0.
但是,以下代码似乎没有编译:
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)
而不是专业化你可以只是重载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编译.