Generic implementation of operator<< function in terms of the dump member function

前端 未结 4 1858
时光说笑
时光说笑 2021-01-05 20:17

All my classes implement a dump member function, e.g.:

struct A {
    template 
    std::basic_ostream &
         


        
4条回答
  •  遥遥无期
    2021-01-05 21:01

    Generally this would be the advisable way, IMO:

    struct A {
        int x = 5;
    
        friend std::ostream & operator<<(std::ostream &os, const A& a){
            return (os << a.x);
        }
    };
    

    Reason: 'friend' functions and << operator overloading: What is the proper way to overload an operator for a class?

    If you really want to have a dedicated dump method, you could define a base class "collecting" dumpable objects.

提交回复
热议问题