如何使预处理器为 __LINE__ 关键字生成字符串?
__FILE__
被 C++ 预处理器替换为“MyFile.cpp”。 我希望将 __LINE__
替换为“256”字符串而不是 256 整数。 不使用我自己编写的函数,例如
toString(__LINE__);
这可能吗?我该怎么做呢?
VS 2008
编辑 我想自动查找并替换
throw std::runtime_error(std::string("exception at ") + __FILE__ + " "+__LINE__);
源代码中的所有 throw;
语句。如果我使用宏或函数将 __LINE__ 转换为字符串,我需要手动修改每个源文件。
__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 I'd like to automatically Find and Replace all throw;
statements with
throw std::runtime_error(std::string("exception at ") + __FILE__ + " "+__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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要双重扩展技巧:
几年后的附录:稍微特意避免可能在异常处理路径中分配内存的操作是一个好主意。鉴于上述内容,您应该能够编写
在编译时而不是运行时执行字符串连接的代码。它仍然会在运行时构造一个 std::string (隐式),但这是不可避免的。
You need the double expansion trick:
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
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.
编辑:为了响应其他答案的请求,我添加了一个非宏版本:
EDIT: In response to request on the other answer, I added a non-macro version: