Do I need multiple template specializations if I want to specialize for several kinds of strings?
-
26-09-2019 - |
Question
For example:
template<typename T>
void write(T value)
{
mystream << value;
}
template<>
void write<const char*>(const char* value)
{
write_escaped(mystream, value);
}
template<>
void write<char*>(char* value)
{
write_escaped(mystream, value);
}
template<>
void write<const std::string&>(const std::string& value)
{
write_escaped(mystream.c_str(), value);
}
This looks like I'm doing it wrong, especially the two variants for const and non-const char*. However I checked that if I only specialize for const char *
then passing a char *
variable will invoke the non-specialized version, when called like this in VC++10:
char something[25];
strcpy(something, "blah");
write(something);
What would be the proper way of doing this?
Solution
You did it the proper way.
char *
and const char *
are two distinct typenames, they require each their own specialization.
OTHER TIPS
C++ compiler treats type T and type const T as different data types Since templates work on data type specifications. You have to write explicit definitions for each explicit data type.
Given that a std::stringstream already handles all of these types, why on earth would you need to specialize for them?
In addition to that, it shouldn't be required of any C++ developer to deal with const char*. Or use memcpy. Just make a std::string out of it. And take a const reference to said std::string. Seriously, are you trying to write C here?