定制cout

jac*_*hab 10 c++ iostream stl

如何从中派生出一个类cout,例如,写入它

new_cout << "message";

相当于

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

Dan*_*ker 31

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__)
Run Code Online (Sandbox Code Playgroud)

因此:

MAGIC_LOG << "here's a message";
MAGIC_LOG << "here's one with a number: " << 5;
Run Code Online (Sandbox Code Playgroud)