将c ++宏重写为函数等

jor*_*gen 6 c++ macros conventions function

我有一个宏,我使用了很多,受到另一个问题的启发:

#define to_string(x) dynamic_cast<ostringstream &> (( ostringstream() << setprecision(4) << dec << x )).str()
Run Code Online (Sandbox Code Playgroud)

这个非常方便,例如在使用字符串输入的函数时:

some_function(to_string("The int is " << my_int));
Run Code Online (Sandbox Code Playgroud)

但是我被告知在C++中使用宏是不好的做法,事实上我在上面的不同编译器上工作时遇到了问题.有没有办法把它写成另一种结构,例如一个函数,它将具有相同的多功能性?

Pet*_*etr 7

您的宏比std::to_string提供更多的可能性.它接受任何合理的<<运算符序列,设置默认精度和十进制基数.兼容的方法是创建一个std::ostringstream可隐式转换为的包装器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);
}
Run Code Online (Sandbox Code Playgroud)

直播:http://coliru.stacked-crooked.com/a/14515cabae729875


Nat*_*ica 6

在C++ 11及更高版本中,我们现在拥有std::to_string.我们可以使用它将数据转换为字符串,并将其附加到您想要的任何内容中.

some_function("The int is " + std::to_string(my_int));
Run Code Online (Sandbox Code Playgroud)