Alex Rivera | Logout

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

Asked 2012-02-28T17:45:01.250
16

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.

Edit
Report

1 Answer

7

Instead of specializing you can just overload writeText() and 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) {}
};

Compiled with g++ v4.6.1.

answered 2012-02-28T18:01:30.897

Your Answer