Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct way to declare/define custom cout-like object

I created my own std::cout-like object that writes both to std::cout and to a log file.

I'm currently defining it like this in a header file, but I'm getting unused variable warnings.

Header file <MyLib/Log.h>

static LOut { };
static LOut lo;

template<typename T> inline LOut& operator<<(LOut& mLOut, const T& mValue)
{
    std::string str{toStr(mValue)};
    std::cout << str;
    getLogStream() << str;
    return mLOut;
}

Usage:

#include <MyLib/Log.h>
...
lo << "hello!" << std::endl;

Should lo be static? Should lo be extern?

Kudos for explaining the correct way of declaring a cout-like object and showing how the main standard library implementations do it.


Edit: by cout-like object, I mean a global variable that is always available after including the corresponding header.

like image 440
Vittorio Romeo Avatar asked Jul 21 '13 16:07

Vittorio Romeo


People also ask

How do you define cout?

The cout object in C++ is an object of class ostream. It is defined in iostream header file. It is used to display the output to the standard output device i.e. monitor. It is associated with the standard C output stream stdout.

How is cout written?

cout is an object of class ostream that represents the standard output stream. It can write characters either as formatted data using for example the insertion operator ostream::operator<< or as Unformatted data using the write member function. Save this answer.

How is STD cout implemented?

std::cout is initialized using a pointer to an instance of some implementation-defined derived class of std::basic_streambuf . If you want more details, you need to specify what implementation you're asking about. It sounds like you won't be satisfied until you see the actual code for a standard library implementation.


1 Answers

std::cout is simply declared as follows:

namespace std {
    extern ostream cout;
}

It is a regular global variable; you can do the same thing yourself. Put an extern declaration of your variable in a header; then define the same variable in a source file and link it to your application:

// mylog.h
extern MyLog mylog;

// mylog.cpp
MyLog mylog(someparams);
like image 70
JohannesD Avatar answered Nov 14 '22 07:11

JohannesD