【问题标题】:Rewriting a c++ macro as a function, etc将 C++ 宏重写为函数等
【发布时间】:2016-01-21 16:34:20
【问题描述】:

我有一个经常使用的宏,灵感来自另一个问题:

#define to_string(x) dynamic_cast<ostringstream &> (( ostringstream() << setprecision(4) << dec << x )).str()

这个非常方便,例如用于接受字符串输入的函数:

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

但是有人告诉我,在 C++ 中使用宏是不好的做法,事实上,我在将上述内容用于不同的编译器时遇到了问题。有没有办法把它写成另一种结构,例如一个函数,哪里会有同样的通用性?

【问题讨论】:

    标签: c++ function macros conventions


    【解决方案1】:

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

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

    【讨论】:

    • 谢谢!但是我需要像上面那样写吗?这比原来的宏有点乱,我得重写相当多的代码。
    • @jorgen 是的。这不是直接替换。他们使用宏的方式是我看到的唯一方法,而无需像上面那样重写代码。
    【解决方案2】:

    您的宏比std::to_string 提供的可能性更多。它接受任何合理的&lt;&lt; 运算符序列,设置默认精度和十进制基数。一种兼容的方法是创建一个 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);
    }
    

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

    【讨论】:

      【解决方案3】:

      讽刺的是,to_string 正是你想要的。

      代替:to_string("The int is " &lt;&lt; my_int)

      你可以写:"The int is " + to_string(my_int)

      这将返回一个string

      [Live Example]

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-12-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-12
        • 2011-01-07
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多