If I have here DATA_T = std::string, I can't compile this code, because of error "no matching function for call to 'to_string'". The function does not allow converting a string to a string. But I need to get the string anyway, how can I work around this error and compile the program?
template <typename DATA_T>
std::string get_string(DATA_T subdata) {
std::string data = "...";
if (typeid(subdata) == typeid(std::string))
data += subdata;
else
data += std::to_string(subdata);
return data;
}
Instead of trying to branch on the type of a template argument inside the body of your function, you can write an overload that will be preferred when the argument is a std::string
.
template <typename DATA_T>
std::string get_string(DATA_T subdata) {
std::string data = "...";
data += std::to_string(subdata);
return data;
}
std::string get_string(std::string subdata)
{
std::string data = "...";
data += subdata;
return data;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With