C++ format macro / inline ostringstream

前端 未结 7 1364
不知归路
不知归路 2020-12-01 03:18

I\'m trying to write a macro that would allow me to do something like: FORMAT(a << \"b\" << c << d), and the result would be a string -- the s

7条回答
  •  没有蜡笔的小新
    2020-12-01 03:58

    Here is what I use. It all fits into one tidy class definition in a header file.

    update: major improvement to the code thanks to litb.

    // makestring.h:
    
    class MakeString
    {
        public:
            std::stringstream stream;
            operator std::string() const { return stream.str(); }
    
            template
            MakeString& operator<<(T const& VAR) { stream << VAR; return *this; }
    };

    Here is how it is used:

    string myString = MakeString() << a << "b" << c << d;

提交回复
热议问题