I've created a small utility function for string conversion so that I don't have to go around creating ostringstream objects all over the place
template<typename T>
inline string ToString(const T& x)
{
std::ostringstream o;
if (!(o << x))
throw BadConversion(string("ToString(") + typeid(x).name() + ")");
return o.str();
}
I want to provide some specialisations of this method for instances where there is no default overloaded << operator for stringstream (i.e. std::pair, std::set, my own classes) and I've run into difficulties with the templating. I will illustrate with the std::pair example, if I want to be able to
string str = ToString(make_pair(3, 4));
the only way I can think of to do it is to define the explicit specialisation for int
template<>
inline string ToString(const pair<int,int>& x)
{
std::ostringstream o;
if (!(o << "[" << x.first << "," << x.second << "]"))
throw BadConversion(string("ToString(pair<int,int>)"));
return o.str();
}
is there a way I can define this for the generic case?
template<>
inline string ToString(const pair<T1,T2>& x)
{
std::ostringstream o;
if (!(o << "[" << x.first << "," << x.second << "]"))
throw BadConversion(string("ToString(pair<T1,T2>)"));
return o.str();
}