1

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

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
};

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

4

1 回答 1

1

第一种方法是完全可行的,只要你 makedoAdoB的成员StreamClass,给他们一个对StreamClass拥有它们的实例的引用(在构造期间)并让它们实现operator<<

最后,doAand的类型应该包含指向ordoB的引用/指针。考虑禁止复制/移动构造函数和赋值运算符。StreamClassStreamClass::Data


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

最后一种方式在语法上是无效的,因为它streamClass不是一个变量模板。

于 2020-12-19T11:32:39.663 回答