问题描述
我想包装 std :: cout
进行格式化,例如:
I'd like to wrap std::cout
for formatting, like so:
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
?
How can I implement this? What type to make 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文件中。
And put MyCout myCout;
into any one .cpp file.
然后您可以像这样使用 myCout
:
You can then use myCout
like this:
myCout << "test" << x << std::endl;
它将调用模板 operator<<
可以进行格式化。
And it will call the template operator<<
which can do the formatting.
当然,如果愿意,还可以为特定类型的特殊格式提供运算符的重载。
Of course, you can also provide overloads of the operator for special formatting of specific types if you want to.
编辑
显然(感谢@soon),对于标准操纵器来说,它还有更多功能超载是必要的:
Apparently (thanks to @soon), for standard manipulators to work, a few more overloads are necessary:
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
我可能会误解了您的原始要求。怎么样(加上上面相同的操纵器重载):
I may have misunderstoor your original requirements slightly. How about this (plus the same manipulator overloads as above):
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;
}
这篇关于如何编写允许表达语法的cout函数包装器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!