简体   繁体   English

如何让预处理器为__LINE__关键字生成一个字符串?

[英]How to make preprocessor generate a string for __LINE__ keyword?

__FILE__ is replaced with "MyFile.cpp" by C++ preprocessor. C ++预处理器将__FILE__替换为“MyFile.cpp”。 I want __LINE__ to be replaced with "256" string not with 256 integer. 我想__LINE__被替换为“256”字符串而不是256整数。 Without using my own written functions like 不使用我自己的书面函数

toString(__LINE__);

Is that possible? 那可能吗? How can I do it? 我该怎么做?

VS 2008 VS 2008

EDIT I'd like to automatically Find and Replace all throw; 编辑我想自动查找和替换所有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. 如果我使用宏或函数将__LINE__转换为字符串,我需要手动修改每个源文件。

You need the double expansion trick: 你需要双扩展技巧:

#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__);

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. 它仍将在运行时构造一个std :: string(隐式),但这是不可避免的。

EDIT : In response to request on the other answer, I added a non-macro version: 编辑 :为了回应其他答案的请求,我添加了一个非宏版本:

#include <iostream>
#include <boost/lexical_cast.hpp>
#include <string>

#define B(x) #x
#define A(x) B(x)

void f(const char *s) {
std::cout << s << "\n";
}

int main() {

   f(A(__LINE__));
   f(boost::lexical_cast<std::string>(__LINE__).c_str());
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM