Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 416
jorgen Avatar asked Oct 22 '15 11:10

jorgen


3 Answers

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));
like image 88
NathanOliver Avatar answered Oct 24 '22 21:10

NathanOliver


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

like image 38
Petr Avatar answered Oct 24 '22 21:10

Petr


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]

like image 37
Jonathan Mee Avatar answered Oct 24 '22 21:10

Jonathan Mee