I have a macro that I use a lot, inspired by another question:
#define to_string(x) dynamic_cast<ostringstream &> (( ostringstream() << setprecision(4) << dec << x )).str()
This one is extremely handy for example in use with functions taking string inputs:
some_function(to_string("The int is " << my_int));
However I've been told that using macros in C++ is bad practice, and in fact I've had problems getting the above to work on different compilers. Is there a way to write this as another construction, e.g. a function, where it will have the same versatility?
In C++11 and greater we now have std::to_string
. We can use that to convert the data into a string an append it to whatever you want.
some_function("The int is " + std::to_string(my_int));
Your macro has more possibilities than std::to_string
offers. It accepts any sensible sequence of <<
operators, sets a default precision and decimal base. A compatible way is to create a std::ostringstream
wrapper that is implicitly convertible to std::string
:
class Stringify {
public:
Stringify() : s() { s << std::setprecision(4) << std::dec; };
template<class T>
Stringify& operator<<(T t) { s << t; return *this; }
operator std::string() { return s.str(); }
private:
std::ostringstream s;
};
void foo(std::string s) {
std::cout << s << std::endl;
}
int main()
{
foo(Stringify() << "This is " << 2 << " and " << 3 << " and we can even use manipulators: " << std::setprecision(2) << 3.1234);
}
Live: http://coliru.stacked-crooked.com/a/14515cabae729875
Ironically, to_string
is what you want here.
Instead of: to_string("The int is " << my_int)
You can write: "The int is " + to_string(my_int)
This will return a string
.
[Live Example]
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