How to properly overload the << operator for an ostream?

前端 未结 5 1288
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-22 04:54

I am writing a small matrix library in C++ for matrix operations. However my compiler complains, where before it did not. This code was left on a shelf for 6 months and in b

5条回答
  •  猫巷女王i
    2020-11-22 05:24

    In C++14 you can use the following template to print any object which has a T::print(std::ostream&)const; member.

    template
    auto operator<<(std::ostream& os, T const & t) -> decltype(t.print(os), os) 
    { 
        t.print(os); 
        return os; 
    } 
    

    In C++20 Concepts can be used.

    template
    concept Printable = requires(std::ostream& os, T const & t) {
        { t.print(os) };
    };
    
    template
    std::ostream& operator<<(std::ostream& os, const T& t) { 
        t.print(os); 
        return os; 
    } 
    

提交回复
热议问题