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

前端 未结 4 1867
时光说笑
时光说笑 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 20:52

    template 
    auto operator<< (std::basic_ostream & str, const T & t) -> decltype(t.dump(str))
    {
        static_assert(std::is_same
                        &>::value, 
                      ".dump(ostream&) does not return ostream& !");
    
        return t.dump(str);
    }
    

    This overloads operator<< only for types that define an appropriate dump member.

    Edit: added static_assert for better messages.

提交回复
热议问题