需求
实现一个类似glog风格支持<<链式调用的log库。
代码
利用的析构函数的特性,每次LOG结束后会自动调用,完成消息拼接。
#include <string>
#include <iostream>
class LOG
{
public:
LOG(int lv)
{
level = lv;
body = "";
}
template<typename type>
LOG& operator<<(type msg)
{
body += std::to_string(msg);
return *this;
}
LOG& operator<<(const char* msg)
{
body += msg;
return *this;
}
~LOG()
{
std::cout << "[" << level << "] " \
<< body << std::endl;
}
private:
int level = 0;
std::string body;
};
int main()
{
// for simplicity, 1 2 3 for INFO WARN ERROR
LOG(1) << "test" << 111;
LOG(2) <<"string: " << float(41*8 + 59%8)/640*1900;
return 0;
}
效果
[1] test111
[2] string: 982.656189
标签:LOG,glog,lv,风格,include,模仿,log
From: https://www.cnblogs.com/azureology/p/18422604