Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compile programm with error "no matching function for call to 'to_string'"? c++

Tags:

c++

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;
}
like image 463
THND Avatar asked Nov 28 '22 21:11

THND


1 Answers

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;
}
like image 87
Nathan Pierson Avatar answered Dec 05 '22 18:12

Nathan Pierson