![](/img/trans.png)
[英]#define print(msg) std::cout << msg << std::endl
[英]A better #define print std::cout<<boost::format
为了快速插入简短的调试语句,我想转向
print("%d %d %s") % i % j % str;
变得更加冗长
std::cout << boost::format("%d %d %s") % i % j % str << std::endl;
提到的#define print std::cout<<boost::format
没有endl,因此,即使我在字符串中添加“ \\ n”,如果在下一行发生崩溃,缓冲区也不会被刷新。
让print("string)
返回xPrint实例并重载xPrint::operator%
的更C ++方式不起作用,因为我无法知道何时进行了最后一次%
调用,现在该打印结果了格式字符串。
注意:我需要boost :: format,所以printf / fflush不会,我希望结果语法简短。
我会建议类似
#define print(x) std::cout << (x) << std::endl
这可以让你做
print(boost::format("%s") % str);
如果您真的坚持上面给出的简短版本,那么我能想到的是:
#include <iostream>
#include <boost/format.hpp>
class Forwarder
{
public:
Forwarder(const std::string& s)
: f(s)
{}
template <typename T>
Forwarder& operator%(const T& t)
{
f % t;
return *this;
// You could even return a reference to f here instead if you wanted
}
~Forwarder()
{
std::cout << f << std::endl;
}
private:
boost::format f;
};
#define print(x, y) { Forwarder f(x); f % y; }
int main()
{
std::string str("Hallo");
int i = 123, j = 456;
print("%s %d %d", str % i % j);
}
编辑这里有一些更多的(可能很危险!)想法,用于破解这样的打印语句。 下面的代码仅用于显示概念,不会按原样编译。 使用风险自负!
a)通过为operator%
添加专用化而不是使用析构函数触发打印来向Forwarder
添加终止语句:
将helper struct定义为终止符(最好在命名空间中,但是您会明白...):
struct END {};
专门化模板:
template <>
Forwarder& Forwarder::operator%<END>(const END& t)
{
std::cout << f << std::endl;
return *this;
}
用法:
print("%s %d %d") % str % i % j % END;
b)使用约束不太严格且从右到左具有关联性的运算符。 您可能必须引入一个辅助类型,尽管它可能是某种日志记录目标。
void operator<<=(Logger& l, const Forwarder& f) { ... }
用法:
DebugLogger <<= Forwarder("%s %d %d") % str % i % j;
c)与上面相同,但使用的是左到右关联的逗号运算符(yuck!)。
void operator,(const Forwarder& f, Logger& l) { ... }
用法:
Forwarder("%s %d %d") % str % i % j, DebugLogger;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.