支持<<宏中的运算符 [英] support << operator in a macro

查看:59
本文介绍了支持<<宏中的运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想实现一个执行以下操作的宏:

I'd like to implement a macro which does the following:

#define report(s)   print(), throw std::runtime_error(s)

我经常调用

print()这个函数来打印一些预定义的东西. s 需要支持:

print() is a function that I always call to print some predefined stuff. s need to support:

report("abc"); // ok
report("abc"<<100); // == report("abc100")

除任何print()输出外,均不应打印其他任何内容.异常将被调用方捕获并打印在此处.

我发现很难支持<<在上面的宏中.

I find it difficult to support << in the above macro.

P.S. report()是一个宏,已经在我的代码库中的每个位置使用了,我只想更改其行为.调用类似report("abc"<< 100);必须被支持.将其定义为函数并添加;"最后看起来不合适.

P.S. report() is a macro already used every where in my code base and I just want to change its behaviour. Calls like report("abc"<<100); have to be supported. define it as a function and add ';' at the end doesn't look appropriate.

推荐答案

也许以下(未经测试!)代码可能是鼓舞人心的

Perhaps the following (untested!) code might be inspirational

#define report(Log) do { std::ostringstream _os; \
  _os << Log << std::flush; print(_os.str()); \
  throw std::runtime(_os.str()); } while(0)

,您可以将其用作 report("x ="<< x);

顺便说一句,您甚至可以使用

BTW, you might even pass the source location using

#define report_at(Log,Fil,Lin)  do { std::ostringstream _os; \
  _os << Fil << ":" << Lin << ": " << Log << std::flush; \
  print(_os.str()); \
  throw std::runtime(_os.str()); } while(0)

(要降低与 _os 发生碰撞的可能性,您甚至可以使用预处理器

(to lower probability of collision with _os you might even replace all its occurrences inside the brace with _os##Lin using preprocessor concatenation)

#define report_at_bis(Log,Fil,Lin) report_at(Log,Fil,Lin)

#define report(Log) report_at_bis(Log,__FILE__,__LINE__)

这显示了宏真正有用的情况之一.

and this shows one of the cases where a macro is really useful.

这篇关于支持&lt;&lt;宏中的运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆