views:

72

answers:

3

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?

+1  A: 

You did it the proper way.

char * and const char * are two distinct typenames, they require each their own specialization.

Didier Trosset
"require" may be a bit strong - they may need separate overloaodings/specilisations if there are other alternative overlaodings/specialisations available.
anon
+1  A: 

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.

Pardeep
A: 

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?

DeadMG
a) Because I want strings handled specially because stringstream doesn't provide a way to read back the string I wrote if it has spaces in it [that I know of]. b) Because I don't want to accidentally introduce a bug by forgetting to add a "std::string()" around my string literal.
romkyns
Re memcpy and stuff: what, not even when writing C++ code that uses a C API? (which I am)
romkyns
If you want to read back the string that you wrote, why not just keep the original string? As for memcpy, the example (of strcpy) that you gave is still an abomination. Fixed-size buffer is begging for overflow. Strcpy is unsafe in as of itself anyway. Why not just use char[] buffer = "lols"? And, if you can't remember to construct an object, then you get a nice compile-time error, easily caught, and definitely worth it considering the safety of std::string over the abomination of const char*.
DeadMG
a) Because the program is not running between the writes and the reads :) b) I apologize profusely for my char[] abomination. c) You don't get the compiler error if there is a template function with the same name (which is the whole point of the question).
romkyns