C++复制流操纵器到其他流

NaC*_*aCl 4 c++ stl stream c++11

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

如果std::ostream没有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;
};
Run Code Online (Sandbox Code Playgroud)

打印a.我知道这个例子是无用的,特别是将整数转换为字符串的其他流似乎没用,但让我们想象一下这不是无用而不是纯粹的非法.

谢谢.

Pio*_*cki 7

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();
}
Run Code Online (Sandbox Code Playgroud)

DEMO