Search code examples
c++templatesoperator-overloadingostream

C++ - trying to overload "<<" operator


I am trying to overload "<<" operator to call 2 methods but compiler gives me an error:

invalid initialization of non-const reference of type 'std::ostream&' 
{aka 'std::basic_ostream<char>&' from an rvalue of type 'void'
        return v.init();

Here is my class definition:

template<class T>
class Vector
{
private:
    std::vector<T> _Vec;
public:
    void fillVector();
    void printElements();
    void init() { fillVector(); printElements(); }
    friend std::ostream& operator<<(std::ostream& os, Vector& v) {
            return v.init();    
};

How can I fix it?


Solution

  • You're doing that wrong.

    This template is misleading. Its name is terrible.
    This extra methods: fillVector, printElements, init are confusing (what exactly they should do?).
    Most probably printElements is missing std::ostream& stream argument (and maybe return type).

    You didn't described what kind of functionality you are trying to implement. Most probably this is what you need:

    template<class T>
    class PrintContainer
    {
    public:
        PrintContainer(const T& container)
        : mContainer { container }
        {}
    
        std::ostream& printTo(std::ostream& stream) const {
            // or whatever you need here
            for (const auto& x : mContainer) {
                 stream << x << ", ";
            }
            return stream;
        }
    
    private:
        const T& mContainer;
    };
    
    template<class T>
    std::ostream& operator<<(std::ostream& os, const PrintContainer<T>& p) {
        return p.printTo(os);
    }