How to define a static operator<<?

前端 未结 4 1002
终归单人心
终归单人心 2021-01-03 06:37

Is it possible to define a static insertion operator which operates on the static members of a class only? Something like:

class MyClass
{
public:
    static         


        
4条回答
  •  青春惊慌失措
    2021-01-03 07:18

    You can't. A class-name / type is not a value in itself, you would need an expression like

    class Foobar {...};
    
    std::cout << Foobar << std::endl;
    

    so that your static operator<< would be usable, but that is not valid C++. The grammar summary at A.4 shows that putting a type's name there is not valid.

    Consider also that operator overloads are just functions with flaky names:

    T  operator<< (T, T)
       ^^^^^^^^^^ flaky name, basically same as:
    T  left_shift (T, T)
    

    And functions in C++ (and most other languages, e.g. C#) can only work on instances of types, not types themselves.

    However, C++ offers templates which have type arguments, howhowever, that would not help you to overload functions upon types.

提交回复
热议问题