记录,如何获得命令结束?

Rel*_*lla 1 c++ logging templates stl std

所以我使用这样的Log类:

#include <stdio.h>
#include <iostream>

class Log
{
public:
    int i;
    Log()
    {
        i = 0;
    }

    template <class T>
    Log &operator<<(const T &v)
    {
        i++;
        std::cout << i << ":"  << v << ";" <<std::endl;
        return *this;
    }
    Log &operator<<(std::ostream&(*f)(std::ostream&)) 
    {
        i++;
        std::cout << i << ":"  << *f << ";" <<std::endl;
        return *this;
    }

    ~Log()
    {
        std::cout << " [end of message]" << std::endl;
    }
};
Run Code Online (Sandbox Code Playgroud)

我用的是:

#include <log.h>

int main()
{
    Log a;
    a << "here's a message" << std::endl;
    a << "here's one with a number: " << 5;
    std::cin.get();
}
Run Code Online (Sandbox Code Playgroud)

我希望我把日志类放到";"时 意思是,如果我有,a << "here's a message" << std::endl;我希望它能够得到它是oune日志消息,a << "here's one with a number: " << 5;是另一个.

它会输出下一条消息:

1:here's a message;
2:
;
3:here's one with a number: ;
4:5;
Run Code Online (Sandbox Code Playgroud)

我想保留它的sintax(无限数量<<,大范围的值类型,在api中没有()周围)但是使它输出:

1:here's a message
;
2:here's one with a number: 5;
Run Code Online (Sandbox Code Playgroud)

怎么办这样的事情?

Pup*_*ppy 5

operator<<返回临时值将放置endl在破坏和转发所有operator<<的主要对象调用.这样,endl保证只调用一次.

class Log
{
struct EndlOnDeath {
    Log* log;
    EndlOnDeath(Log* ptr)
        : log(ptr) {}
    template<typename T> EndlOnDeath& operator<<(const T& val) {
        (*log) << val;
    }
    ~EndlOnDeath() {
        (*log) << std::endl;
    }
};

public:
    int i;
    Log()
    {
        i = 0;
    }

    template <class T>
    EndlOnDeath operator<<(const T &v)
    {
        i++;
        std::cout << i << ":"  << v << ";";
        return this;
    }
    Log &operator<<(std::ostream&(*f)(std::ostream&)) 
    {
        i++;
        std::cout << i << ":"  << *f << ";" <<std::endl;
        return *this;
    }

    ~Log()
    {
        std::cout << " [end of message]" << std::endl;
    }
};
Run Code Online (Sandbox Code Playgroud)