I'm trying to define a toString helper method that should work either by using the << operator if available, or using a range-loop to print containers. I thought that C++11 and template magic would just sort of figure out what to use, but instead I'm getting the error "Redefinition of 'toString'".
/** to string via o<<value operations */
template<class T>
inline static std::string toString(const T& value) {
return (std::stringstream() << value).str();
}
/** to string via for each and tostring */
template<class T>
inline static std::string toString(const T& container) {
std::stringstream stream;
std::string delim = "";
stream << "{";
for (const auto& element : container) {
stream << delim << toString(element);
delim = ",";
}
stream << "}";
return stream.str();
}
I guess the definitions have to be separated somehow. It's possible to specialize the second template to vector, which works, but then it only works on vectors. So I tried to find a way to do it with traits and enable_if, which firstly I couldn't figure out, and secondly there doesn't seem to be a trait for 'supports range loop' or 'supports << operator'.