I am writing common function to convert type T to string:
when T is numeric type just use std::to_string
when others use stringstream operator <<
when T is std::string just return T
template <typename Numeric>
string to_str1(Numeric n){
return std::to_string(n);
}
template <typename NonNumeric>
std::string to_str2(const NonNumeric& v){
std::stringstream ss;
ss << v;
return ss.str();
}
// if T is string just return
std::string to_str2(const std::string& v){
return v;
}
template<typename T>
string to_str(const T& t){
if(std::is_integral<T>::value){
return to_str1(t);
}else{
return to_str2(t);
}
}
test usage:
int a = 1101;
cout << to_str(a) << endl;
string s = "abc";
cout << to_str(s) << endl; // should use to_str2(const std::string& v),but compile error
but compile error:
In instantiation of string to_str1 ..... no matching function for call to to_string(std::__cxx11::basic_string
I don't know why this error, ?
if constexprinstead ofif, since the latter will validate both branches even if the condition is known at compile-time.