我想定义一个宏“BracketCout”,它会在流参数之前或之后自动插入预设字符串值:
#define LEFT_BOUNDARY "["
#define RIGHT_BOUNDARY "]"
#define BracketCout ??????
BracketCout << "123" << "abc"; // outputs "[123abc]"
那怎么可能呢?
我想定义一个宏“BracketCout”,它会在流参数之前或之后自动插入预设字符串值:
#define LEFT_BOUNDARY "["
#define RIGHT_BOUNDARY "]"
#define BracketCout ??????
BracketCout << "123" << "abc"; // outputs "[123abc]"
那怎么可能呢?
由于我已经在使用日志类,因此实现 Code Clown 的建议相当简单。这是记录器类的简化版本:
#define LOG Log().out()
class Log
{
public:
Log() {}
virtual ~Log();
std::ostringstream& out();
public:
std::ostringstream os;
};
std::ostringstream& Log::out()
{
os << "["; // beginning
return os;
}
Log::~Log() // destructor
{
os << "]";
std::cout << os.str() << std::endl;
}
要使用它,我会打电话
LOG << "abc" << 123; // prints "[abc123]"
像这样。
#include <iostream>
#include <sstream>
class BracketOut
{
public:
BracketOut()
{
m_stream << '[';
}
~BracketOut()
{
std::cout << m_stream.str() << ']' << std::endl;
}
std::ostringstream& get() { return m_stream; }
std::ostringstream m_stream;
private:
};
int main()
{
BracketOut().get() << "Hello World";
}