I have a header file that I include into my main.cpp file. I want to set some flags when this file is included.

std::cout.flags(std::ios::boolalpha);

I want to set that automatically how can I do this? I tried:

#ifdef DEFINES_HPP_INCLUDED
    std::cout.flags(std::ios::boolalpha);
#endif


//Gives me the error:
//error: 'cout' in namespace 'std' does not name a type|

Or better yet, how can I enable that for all streams automatically?

Recommended Answers

All 3 Replies

It is generally not recommended to do this at all. There is always the danger of the static initialization order fiasco. I'm not sure how safe it is to do this for a standard component like cout.

The safest thing is to just define a function that will perform this task, and you can make that function for all stream types, like so:

void init_stream_flags(std::ios_base& str) {
  str.flags(std::ios::boolalpha);
};

But, then, of course, that function has to be called either in main() or elsewhere on all streams that you will be using.

If you wanted to actually get the behavior you described (static initialization) for cout, you would need to wrap the functionality inside a class constructor, and construct a static object of that class. As so:

class stream_initializer {
  public:
    stream_initializer() {
      init_stream_flags(std::cout);
    };
};

static const stream_initializer str_init_object = stream_initializer();

The construction of the stream initializer will call the init_stream_flags on std::cout. Of course, that assumes that std::cout itself has already been initialized, which is not guaranteed, and thus, not a safe assumption to make.

Ahh that seems like a headache. Uh what could happen if it's not initalized and I do assume? Though I will not, I just want to know.

Uh what could happen if it's not initalized and I do assume?

Anything can happen, it is undefined behavior. The more likely outcomes are that nothing happens (and your flag setup is inaffective), or that your program crashes before it even starts executing the main() function.

Whether cout will be initialized at the point where you set the flags depends on the compiler, the platform and the order in which the linker decides to arrange things. Quite unpredictable.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.