为单个 class 制作多个 operator<<() 定义

Making multiple operator<<() definition for a single class

所以基本上这就是我想要做的:

void someMethod() {
    StreamClass streamClass{};

    streamClass << "Something" << "\n"; //do something
    streamClass.doA << "Something" << "\n"; //do another thing
    streamClass.doB << "Something" << "\n"; //do something else

    //If the first one is impossible, what about this?
    streamClass << "Something" << "\n"; //do something
    streamClass::doA << "Something" << "\n"; //do another thing
    streamClass::doB << "Something" << "\n"; //do something else

    //Or this?
    streamClass<enumA> << "Something" << "\n"; //do something
    streamClass<enumB> << "Something" << "\n"; //do another thing
    streamClass<enumC> << "Something" << "\n"; //do something else
}

头文件:

class StreamClass {
public:
    StreamClass(); //Init class
    //... and many other things
    template<typename T>
    StreamClass& operator<<(T t) {
        //... do something that uses data and t
    }
    //And do something here?
protected:
    Data data; //some data owned by this object
};

所以,有没有办法做这样的事情?以及如何以最快的方式做到这一点?

第一种方式完全可行,只要让doAdoB成为StreamClass的成员,给他们一个StreamClass实例的引用他们(在施工期间)并让他们实施 operator<<.

最后,doAdoB 的类型应该持有一个 reference/pointer 到 StreamClassStreamClass::Data。考虑禁止 copy/move 构造函数和赋值运算符。


第二个选项在语法上是有效的,但要求 doAdoB 是静态的,这最终使得不可能同时具有两个具有不同行为的 StreamClass 实例.

鉴于 streamClass 不是变量模板,最后一种方法在语法上是无效的。