Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

customize cout

Tags:

c++

iostream

stl

How can I derive a class from cout so that, for example, writing to it

new_cout << "message";

would be equivalent to

cout << __FUNCTION__ << "message" << "end of message" << endl;

like image 425
jackhab Avatar asked Mar 23 '09 16:03

jackhab


People also ask

What is cout type in C++?

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 do you use std cout?

std::cout is used to output a value (cout = character output) std::cin is used to get an input value (cin = character input) << is used with std::cout, and shows the direction that data is moving (if std::cout represents the console, the output data is moving from the variable to the console).

What is the library for cout?

The cout command is a data stream which is attached to screen output and is used to print to the screen, it is part of the iostream library.

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.


2 Answers

class Log
{
public:
    Log(const std::string &funcName)
    {
        std::cout << funcName << ": ";
    }

    template <class T>
    Log &operator<<(const T &v)
    {
        std::cout << v;
        return *this;
    }

    ~Log()
    {
        std::cout << " [end of message]" << std::endl;
    }
};

#define MAGIC_LOG Log(__FUNCTION__)

Hence:

MAGIC_LOG << "here's a message";
MAGIC_LOG << "here's one with a number: " << 5;
like image 150
Daniel Earwicker Avatar answered Oct 14 '22 00:10

Daniel Earwicker


#define debug_print(message) (std::cout << __FUNCTION__ << (message) << std::endl)

This has the advantage that you can disable all debug messages at once when you're done

#define debug_print(message) ()
like image 34
soulmerge Avatar answered Oct 14 '22 00:10

soulmerge