C ++宏'##'在'->'之后不起作用操作员 [英] C++ macro '##' doesn't work after '->' operator
问题描述
我有一个shared_ptr对象x,它具有如下get和set方法:
I have a shared_ptr object x, which has get and set methods as follows:
x->a_value();
x->set_a_value();
x->b_value();
x->set_b_value();
当我尝试定义宏时:
#define MAC(type) \
x->set_##type##_value(val);
MAC(a)
它工作正常,但是当我这样做时:
It works fine, but when I do:
#define MAC(type) \
x->##type##_value();
MAC(a)
它给出以下编译错误:
pasting formed '->a', an invalid preprocessing token
it gives the following compile error:
pasting formed '->a', an invalid preprocessing token
推荐答案
预处理器处理令牌"-喜欢名称和运算符.
The preprocessor works on "tokens" - likes names and operators.
##
运算符通过将较小的部分粘贴在一起来创建新令牌.在第一个示例中,set_##type##_value
变为set_a_value
,这是有效的令牌.
The ##
operator creates a new token by pasting smaller parts together. In the first example set_##type##_value
becomes set_a_value
, which is a valid token.
在第二个示例中,->##type##_value
将变为->a_value
,这不是是有效的预处理器令牌.应该是两个令牌.
In the second example ->##type##_value
would become ->a_value
, which is not a valid preprocessor token. It ought to be two tokens.
如果仅将行设为x->type##_value();
,它将正常工作.您将获得单独的令牌x
,->
,a_value
,(
,)
和;
.
If you just make the line x->type##_value();
it should work. You get the separate tokens x
, ->
, a_value
, (
, )
, and ;
.
这篇关于C ++宏'##'在'->'之后不起作用操作员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!