Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I store a reference to `std::cout` as a class member

Tags:

c++

cout

I'm using a class meant to be used like this:

Output() << "Hello.\n";

In its operator<< I explicitely use std::cout, but I'd like to have a static class member that resolves to `std::cout´ so I can do stuff like this:

copy(some_string_set.begin(), some_string_set.end(), ostream_iterator<string>(Output::m_stream, ", "));

or something similar (I can't fix the bottom line until I get the static data member fixed.

I even tried auto, but GCC threw a

error: 'std::cout' cannot appear in a constant-expression

at me. How can I do what I want? (the point is not having to use std::cout all through my code, but have all output go through the Output class)

like image 723
rubenvb Avatar asked Feb 22 '11 17:02

rubenvb


1 Answers

struct Output
{
    static ostream& stream;
};

ostream& Output::stream = cout;

int main()
{
    Output::stream << "hey";
}

Works fine here.

like image 138
Stefan Monov Avatar answered Oct 03 '22 07:10

Stefan Monov