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 is very convenient, for example, when using functions that accept string inputs:

 some_function(to_string("The int is " << my_int)); 

However, I was told that using macros in C ++ is a bad practice, and in fact I had problems getting them to work on different compilers above. Is there a way to write this as another construct, for example. function, where will it have the same versatility?

+6
source share
3 answers

In C ++ 11 and above, we now have std::to_string . We can use this to convert the data to a string, adding them to what you want.

 some_function("The int is " + std::to_string(my_int)); 
+6
source

Your macro has more features than std::to_string . It accepts any reasonable sequence of << operators, sets the standard precision and decimal base. A compatible way is to create the std::ostringstream , which is implicitly converted 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

+7
source

Oddly enough, 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 ]

+2
source

All Articles