Search code examples
c++operator-overloadingostream

How would I make two ways to output something with <<?


For example, if I wanted to have a default version of outputting with << and a detailed version.

myClass myObject(//Constructor parameters);

cout << myObject << "\n";
cout << myObject.detailed << "\n";

I tried making a modifier within my class but that didn't seem to work.

class myClass {
public:
   friend std::ostream& operator<<(std::ostream& output, const myClass& myObject);
   std::ostream& detailed(std::ostream& output);
}

That gave the error "Reference to non-static member function must be called".


Solution

  • I think my approach is the same as what @RemyLebeau but more generic.

    #include <iostream>
    #include <string>
    
    //---------------------------------------------------------------------------------------------
    // class templated to be able to apply
    // detailed mechanism to different types
    
    template<typename type_t>
    class detailed
    {
    public:
        detailed(const type_t& object) : 
            m_object{ object } 
        {
        }
    
        friend std::ostream& operator<<(std::ostream& os, const detailed<type_t>& detailed_object)
        {
            detailed_object.m_object.detailed_output(os);
            return os;
        }
    
    private:
        const type_t& m_object;
    };
    
    //---------------------------------------------------------------------------------------------
    // like your class
    
    struct test_class_t
    {
    public:
        friend std::ostream& operator<<(std::ostream& os, const test_class_t& object)
        {
            os << object.basic;
            return os;
        }
    
        void detailed_output(std::ostream& os) const // <- const is important
        {
            os << basic << ", " << details;
        }
    
    private:
        std::string basic{ "basic" };
        std::string details{ "details" };
    };
    
    //---------------------------------------------------------------------------------------------
    
    int main()
    {
        test_class_t object;
        std::cout << detailed{object} << "\n";
    }