Modern pattern for writing a custom operator

Note added later: After some experimentation, I realized that I don't need to overload the r-value of ostream, the library does it for me already. You only need to have an l-value version, and the library has some r-value version, which is redirected to the implemented overload.

So in C ++ 11 this is allowed std::ofstream("file") << A{}

even if no r-value overload is user-defined.


Usually in C ++ we used the so called ostream operator<<

like this:

class A {
    int impl_;
    friend std::ostream& operator<<(std::ostream& os, A const& self){
       return os << "A:" << self.impl_;
    }
};

      

However, now, post C ++ 11, there are r-value references, and essentially built-in types can be cast to the r-value of std::ostream

references. This is now allowed:

int i = 5;
std::ofstream("file") << i;

      

(I don't know if this was a particular overload.)

Does this mean that for consistency, you should define both operators for your custom classes? Like this,

class A {
    int impl_;
    friend std::ostream& operator<<(std::ostream& os, A const& self) {
       return os << "A:" << self.impl_;
    }
    friend std::ostream&& operator<<(std::ostream&& os, A const& self) {
       os << "A:" << self.impl_; 
       return std::move(os);
    }
};

      

or more orderly,

class A {
    int impl_;
    friend std::ostream& operator<<(std::ostream& os, A const& self) {
       return os << "A:" << self.impl_;
    }
    friend std::ostream&& operator<<(std::ostream&& os, A const& self) {
       return std::move(os << self); // calls the other overload
    }
};

      

What is the recommended way of overloading operator<<

currently in C ++ 11?

+3


source to share





All Articles