我想包装 std::cout
以进行格式化,如下所示:
mycout([what type?] x, [optional args]) {
... // do some formatting on x first
std::cout << x;
}
并且仍然能够使用像
这样的富有表现力的语法mycout("test" << i << endl << somevar, indent)
而不是被迫像这样更冗长
mycout(std::stringstream("test") << i ...)
我该如何实现?制作什么类型的 x
?
编辑:增加了对可选参数的考虑
最佳答案
这个怎么样:
struct MyCout {};
extern MyCout myCout;
template <typename T>
MyCout& operator<< (MyCout &s, const T &x) {
//format x as you please
std::cout << x;
return s;
}
然后放MyCout myCout;
进入任何一个 .cpp 文件。
然后您可以使用 myCout
像这样:
myCout << "test" << x << std::endl;
它会调用模板 operator<<
可以进行格式化。
当然,如果需要,您也可以为特定类型的特殊格式提供运算符重载。
编辑
显然(感谢@soon),要使标准操纵器正常工作,还需要一些重载:
MyCout& operator<< (MyCout &s, std::ostream& (*f)(std::ostream &)) {
f(std::cout);
return s;
}
MyCout& operator<< (MyCout &s, std::ostream& (*f)(std::ios &)) {
f(std::cout);
return s;
}
MyCout& operator<< (MyCout &s, std::ostream& (*f)(std::ios_base &)) {
f(std::cout);
return s;
}
编辑 2
我可能稍微误解了您最初的要求。这个怎么样(加上与上面相同的操纵器重载):
struct MyCout
{
std::stringstream s;
template <typename T>
MyCout& operator << (const T &x) {
s << x;
return *this;
}
~MyCout() {
somehow_format(s);
std::cout << s.str();
}
};
int main() {
double y = 1.5;
MyCout() << "test" << y;
}
关于c++ - 如何为允许表达语法的 cout 编写函数包装器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16444119/