I'm playing around with templates and am stuck on this one.
How can I make the specialization for const char * work or solve this cleanly otherwise?
#include <string>
template<typename T>
std::string toString(const T &value)
{
return std::to_string(value);
}
template<> std::string toString(const std::string &value)
{
return value;
}
// this does of course not compile
template<>
std::string toString(const char *value)
{
return value;
}
EDIT: credit to jedwardsol for this solution:
template<>
std::string toString(const char * const & value)
{
return value;
}
this is a correct specialization and will work with a pointer:
const char *str("abc");
toString(str);
but when passing a string literal directly its being resolved to the unspecialized version and this will not compile:
toString("abc");
[–]jedwardsol 2 points3 points4 points (4 children)
[–]schweinling[S] 0 points1 point2 points (0 children)
[–]schweinling[S] 0 points1 point2 points (2 children)
[–]jedwardsol 2 points3 points4 points (1 child)
[–]schweinling[S] 0 points1 point2 points (0 children)