error: no matching function for call to ‘to_string(std::basic_string<char>&)’
std::to_string
only works on fundamental numeric types.
If you need a more generic function, boost::lexical_cast
will work on many more types - effectively any type that can be sent to an iostream
.
#include <boost/lexical_cast.hpp>
...
private_string_field = boost::lexical_cast<std::string>(value);
There is no to_string
for basic string. It would have nothing to do.
After Benjamin Lindley's suggestion I would consider the following design, use to_string
but provide default template:
#include <iostream>
#include <string>
struct Type {
explicit operator std::string() const{
return std::string("I am type");
}
};
namespace std {
template <typename T>
string to_string(const T& value) {
return string(value);
}
}
int main(int argc, char **argv) {
// this is what would be in class
Type x;
std::string private_string_field;
private_string_field = std::to_string(42);
std::cout << private_string_field << std::endl;
private_string_field = std::to_string(x);
std::cout << private_string_field << std::endl;
return 0;
}
By default it tries to cast the operand to a string. This way custom types can provide their own conversion. Alternative design would be to internally use stringstream
and operator<<
for conversions, like this:
#include <iostream>
#include <string>
#include <sstream>
struct Type {
friend std::ostream& operator<<(std::ostream& out, const Type& value){
return out << "Type through operator<<";
}
};
template <class T>
std::string to_str(const T& value) {
std::string ret;
std::ostringstream ss;
ss << value;
ret = ss.str();
return ret;
};
int main(int argc, char **argv) {
// this is what would be in class
Type x;
std::string private_string_field;
private_string_field = to_str(42);
std::cout << private_string_field << std::endl;
private_string_field = to_str(x);
std::cout << private_string_field << std::endl;
return 0;
}