我有如下簡單的日誌記錄類。連接兩個C++語句
#include <iostream>
#include <string>
using namespace std;
class log
{
public:
log(){};
~log(){};
log & operator << (int x){ cout << x; return * this;}
log & operator << (string x){ cout << x; return * this;}
log & operator << (log & (log::*pf)()){ (this->*pf)(); return * this;}
log & end() { cout << "\r\n"; return * this;}
};
log l;
#define end &log::end;
#define error(z) l << "ERROR " z << end;
#define warn(z) l << "WARN " z << end;
int main()
{
int y = 20;
error (<< y);
}
有沒有什麼辦法可以像我這樣寫我的代碼?
error << y;
這裏
基本思路,是爲了避免用戶使用宏年底
即我不希望用戶編寫類似下面
error << y << end;
做你想做的事嗎?按照預期使用'<<'運算符。或者只提供輸出所需前綴的'error()'和'warn()'函數。這裏不需要宏! – TypeIA
您可能想看看[boost.log](http://www.boost.org/doc/libs/1_55_0/libs/log/doc/html/index.html)。 –
爲什麼不從ostream派生類日誌並重載運算符<<,以便在給定的上下文中表現如此? – jpmuc