How can I use template specialization in c++ classes, and why this doesn't compile?

Tibi picture Tibi · Feb 28, 2012 · Viewed 11.4k times · Source

I am working on a XmlWriter class, and I wanted to be able to output attributes or text in most standard data formats (strings, integers, floating point numbers etc). To achieve this, I am using a file stream.

For the bool data type, I wanted to specify a specialization to the template, so that it outputs true and false instead of 1 and 0.

However, the following code doesn't seem to compile:

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

I don't understand, why all these errors, since I used the correct syntax presented on various websites on the internet?

I am using Cygwin GCC.

Answer

Robᵩ picture Robᵩ · Feb 28, 2012

explicit specialization in non-namespace scope 'class Strategy::IO::XmlWriter'

Try moving the specialization into namespace scope?

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) {
}