【问题标题】:C++ copy stream manipulator to other streamC ++复制流操纵器到其他流
【发布时间】:2014-12-30 06:04:56
【问题描述】:

想象一个std::ostream& operator<< 想用数字做一些事情。为此,有人可能想要使用std::hex,而其他人可能想要不使用,无论如何,任何操纵器都是可能的。

如果没有 ostream 的文本内容作为参数传递,我如何将它们复制到另一个 std::ostream?我只需要操纵器

所以我想要std::cout << std::hex << someCoolClass(10)someCoolClass 的样子

struct someCoolClass
{
    someCoolClass(int i) : _i(i)
    {}

    friend std::ostream& operator<<(std::ostream& os, const someCoolClass& rhs)
    {
        std::stringstream ss;
        //magically copy manipulators of os
        ss << _i;
        return os << ss.str();
    }
private:
    int _i;
};

打印a。我知道这个例子是无用的,尤其是另一个将整数转换为字符串的流似乎没用,但让我们想象这不是无用的,也不是纯粹的废话。

谢谢。

【问题讨论】:

    标签: c++ c++11 stl stream


    【解决方案1】:

    ios::copyfmt

    friend std::ostream& operator<<(std::ostream& os, const someCoolClass& rhs)
    {
        std::stringstream ss;
        ss.copyfmt(os);        // <- copy formatting
        ss << rhs._i;
        return os << ss.str();
    }
    

    DEMO

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-03
      • 2011-06-05
      • 1970-01-01
      • 2010-10-22
      • 1970-01-01
      相关资源
      最近更新 更多