如何使预处理生成__LINE__关键字的字符串? [英] How to make preprocessor generate a string for __LINE__ keyword?

查看:139
本文介绍了如何使预处理生成__LINE__关键字的字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

__ FILE __ 由C ++预处理器替换为MyFile.cpp。
我想将 __ LINE __ 替换为256字符串而不是256整数。
不使用我自己编写的函数

__FILE__ is replaced with "MyFile.cpp" by C++ preprocessor. I want __LINE__ to be replaced with "256" string not with 256 integer. Without using my own written functions like

toString(__LINE__);

这是可能吗?我如何做?

Is that possible? How can I do it?

VS 2008

EDIT 自动查找并替换 throw; 语句

throw std::runtime_error(std::string("exception at ") + __FILE__ + " "+__LINE__);

。如果我使用宏或函数将 __ LINE __ 转换为字符串,我需要手动修改每个源文件。

in my sources. If I use macro or function to convert __LINE__ into a string I'll need to modify each source file manually.

推荐答案

您需要双重扩展技巧:

#define S(x) #x
#define S_(x) S(x)
#define S__LINE__ S_(__LINE__)

/* use S__LINE__ instead of __LINE__ */

附录,几年后:最好不要使用某种方式避免在异常处理中分配内存的操作路径。鉴于上述,你应该能够写

Addendum, years later: It is a good idea to go a little out of one's way to avoid operations that may allocate memory in exception-handling paths. Given the above, you should be able to write

throw std::runtime_error("exception at " __FILE__ " " S__LINE__);

这将在编译时执行字符串连接,而不是运行时。它仍然会在运行时构造一个std :: string(隐式),但这是不可避免的。

which will do the string concatenation at compile time instead of runtime. It will still construct a std::string (implicitly) at runtime, but that's unavoidable.

这篇关于如何使预处理生成__LINE__关键字的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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