所以我有一个简单的C++日志类。
class Log{
public:
Log(const int& msgLevel = 1){
this->msgLevel = msgLevel;
}
template <class T>
Log& operator<<(const T& v){
if (msgLevel<=level) {
std::cout << v;
}
return *this;
}
~Log(){
}
static int level;
int msgLevel;
};
int Log::level = 1;
我可以这样用它:
Log(1)<<"My debug info: "<<otherVariable;
问题是当我尝试使用endl
时
Log(1)<<"My debug info: "<<otherVariable<<endl;
我知道这个错误:
error C2678: binary '<<' : no operator found which takes a left-hand operand of type 'Log' (or there is no acceptable conversion)
要解决这个错误,我需要向类添加另一个方法,如下所示:
// For manipulators like endl
Log& operator<< (ostream& (*pf) (ostream&)) {
if (msgLevel<=level) {
cout << pf;
}
return *this;
}
但是添加这个方法仅仅是为了处理endl
,对我来说似乎有点过分了。还有什么更好的选择吗?
另一种选择是使用"\n“而不是endl;
发布于 2014-02-16 15:11:22
因为endl
是一个函数模板,所以简单版本的operator<<
不够好,因为它可以通过为endl
使用不同的模板参数来匹配多种方法。添加第二个重载可能是您所能做的最好的。
但是,您可以将常见的逻辑分解出来,如:
template <class T>
Log& operator<<(const T& v){ return write(v); }
Log& operator<<(ostream& (*v)(ostream&)){ return write(v); }
template <typename T>
Log& write(const T &v)
{
if (msgLevel<=level) {
std::cout << v;
}
return *this;
}
https://stackoverflow.com/questions/21812676
复制相似问题