C ++连接__FILE__和__LINE__宏? [英] C++ concatenating __FILE__ and __LINE__ macros?
问题描述
我想要我的例外消息包含关于异常位置的信息。
所以我想有一些类似的东西。
#define LOCATION __FILE__:__LINE__
throw std :: exception(std :: string(ABCD。 );
这个定义显然是不正确的。如何实现这一点?
您需要双宏键技术(在两个级别展开该宏):
#define S1(x)#x
#define S2(x)S1(x)
#define LOCATION __FILE__:S2(__ LINE__)
为什么?
$ b b
简短答案:
您需要在两个级别中展开 __ LINE __
p> 长回答:
首先,使用操作符#
em 宏,它必须后跟一个宏参数, __ LINE __
不是参数,否则编译器会抱怨它是一个杂散运算符。
其次, __ LINE __
本身是一个宏并且包含当前行号,应该将其扩展为使用#
,否则,您将得到__ LINE __
而不是数字。
宏 S2(__ LINE __)
将 __ LINE __
扩展到行号,然后将行号传递 #x
。
I want my exception messages to contain info about the exception location.
So I would like to have some like thing this.
#define LOCATION __FILE__ " : " __LINE__
throw std::exception(std::string("ABCD. ") + LOCATION);
That define is obviously incorrect. How to achieve this?
You need double-macro-stringy technique (Expand that macro in two levels):
#define S1(x) #x
#define S2(x) S1(x)
#define LOCATION __FILE__ " : " S2(__LINE__)
Why?
Short answer:
You need expand __LINE__
in two levels, before passing it to #x
.
Long answer:
First of all, using operator #
in a function-like macro, it must followed by a macro parameter and __LINE__
is not a parameter, otherwise compiler complains it's a stray operator.
Second, __LINE__
itself is a macro and contains current line number, it should be expanded to the number before using it with #
, otherwise, you will get string "__LINE__"
instead of a number.
Macro S2(__LINE__)
expands __LINE__
to a line number, then we pass the line number to #x
.
这篇关于C ++连接__FILE__和__LINE__宏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!