Dalton
Dalton

Reputation: 181

Why is the output operator 'os << value' and not 'value >> os'?

I am learning about streaming. The standard streams provide the << operator which can be declared as:

ostream& operator<<(stream& os, CLASS& rc);  

Why is it impossible to declare it as this?

ostream& operator>>(CLASS& rc, stream& os); 

Then I may be able to do something like:

rc.something >> os;

as part of its implementation.


Edit as people have helped me learn more about this, I am thankful.

However I am stuck at how to implement actually it.

I have tried

ostream& operator >> (const SomeClass& refToCls, stream& os)
{
   refToCls.iVar >> os;
   return os;
}

but it fails. How can I fix it?

Upvotes: 3

Views: 151

Answers (2)

UncleBens
UncleBens

Reputation: 41351

Here's how you can do it without worrying about associativity, with a helper class to collect the inputs and then send it to ostream:

#include <iostream>
#include <string>
#include <sstream>
#include <algorithm>

class ReversePrinter
{
    std::string acc;
public:
    template <class T>
    ReversePrinter(const T& value)
    {
        *this >> value;
    }

    template <class T>
    ReversePrinter& operator>>(const T& value)
    {
        std::stringstream ss;
        ss << value;
        acc += ss.str();
        return *this;
    }
    std::ostream& operator>>(std::ostream& os)
    {
        std::reverse(acc.begin(), acc.end());
        return os << acc;
    }
};

struct R
{
    template <class T>
    ReversePrinter operator>>(const T& value) {
        return ReversePrinter(value);
    }
};

int main()
{
    std::string name = "Ben";
    int age = 14;
    const char* hobby = "reading backwards";
    R() >> "Hello, my name is " >> name >> "\nI'm " 
        >> age >> " years old and I like " >> hobby >> std::cout;
}

Upvotes: 1

Yakov Galka
Yakov Galka

Reputation: 72519

In fact it's possible to define

ostream& operator>>(CLASS& rc, ostream& os);

But then you must chain it like this:

a >> (b >> (c >> str));

The >> operator is left-associative, so by default this:

a >> b >> c >> str;

is equivalent to:

((a >> b) >> c) >> str;

which has a wrong meaning.

Upvotes: 7

Related Questions