Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Wrap cin and cout in class - Overload << and >> operators

I am trying to make a Console class. I would like to wrap cin and cout in the class and overload the << and >> operators. So I could use the class as such:

// Output
Console << "Call cout from Console" << endl;

// Input
string str;
Console >> str; // Call cin

My best guess was:

class Console {
//...
public:
    ostream& operator<< (ostream& os)
    {
        cout << os;
        return &cout;
    }
    //...
};

But I know that's wrong, how could I overload the operators to use the Console class as both cin and cout?

like image 229
Brandon Miller Avatar asked Dec 21 '22 16:12

Brandon Miller


2 Answers

I got a working code that can handle the stream manipulators. You can see my code in action in this Ideone page

Here is the code:

#include <iostream>

typedef std::ostream& (*manip) (std::ostream&);

class console {

};

template <class T> console& operator<< (console& con, const T& x) { std::cout << x; return con; }
template <class T> console& operator>>(console& con,  T& x) { std::cin >>x; return con; }
console& operator<< (console& con, manip manipulator){ std::cout<<manipulator; return con;}

int main() {
    console c;
    int a,b;
    c>>a>>b;
    c << "hello world"<<std::endl<<std::hex<<(a+b)<<std::endl;
}

Thanks @MooingDuck for the discussion that led me to a working answer and @111111 for the start point.

like image 186
André Oriani Avatar answered Dec 24 '22 01:12

André Oriani


I don't know why would want to do such a thing but it isn't the stream you need to capture but the other type. But if this is just to make std::cout and std::cin more convenient I wouldn't bother.

class console {

};

template<typename T>
console& operator<<(console con, const T& val) {
     std::cout << val;
     return con;
}

console c;
c << "hello world\n";
like image 42
111111 Avatar answered Dec 24 '22 01:12

111111