Even though in a template I can have any type, the function to_string
does not work on basic strings:
for example:
std::string str("my string");
my_class(str);
with this functor definition:
template<class valuetype>
void operator()(valuetype value)
{
...
private_string_field = std::to_string(value);
does not work. here is the error:
error: no matching function for call to ‘to_string(std::basic_string&)’
What is the best way to avoid it.
In advance, I request avoid linking to irrelevant questions just because of a few common keywords.
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;
}
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