How to save a link to `std :: cout` as a member of a class

I am using a class designed to be used as follows:

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

operator<<I explicitly use it in my own std::cout, but I want to have a static member of the class that resolves `std :: cout ', so I can do things like this:

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

or something similar (I cannot fix the bottom line until I get a fixed data item.

I even tried auto, but GCC quit

error: 'std :: cout' cannot be displayed in constant expression

I have. How can I do what I want? (the point should not use std::couteverything through my code, but all the output goes through the Output class)

+3
source share
3 answers
struct Output
{
    static ostream& stream;
};

ostream& Output::stream = cout;

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

It works great here.

+6

std::ostream*.

. , , , .

+7

You must save std::ostream &.

+4
source

Source: https://habr.com/ru/post/1793931/


All Articles