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.
Generics are generic until the types are substituted for them at runtime. Templates are specialized at compile time so they are not still parameterized types at runtime. The common language runtime specifically supports generics in MSIL.
C++ templates can't use normal run-time C++ code in the process of expanding, and suffer for it: for instance, the C++ factorial program is limited in that it produces 32-bit integers rather than arbitrary-length bignums.
Class Templates like function templates, class templates are useful when a class defines something that is independent of the data type. Can be useful for classes like LinkedList, BinaryTree, Stack, Queue, Array, etc. Following is a simple example of a template Array class.
Templates are the foundation of generic programming, which involves writing code in a way that is independent of any particular type. A template is a blueprint or formula for creating a generic class or a function.
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) {
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With