Search code examples
c++functionmacrosconventions

Rewriting a c++ macro as a function, etc


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?


Solution

  • 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));