C ++中定义代码中##的含义是什么?

时间:2013-05-13 05:15:54

标签: c++ c-preprocessor

#define DECLARE_DELETE_PTR(type) \
void DeletePtr_##type(string &operand) \
{\
}\

C ++宏定义中##的含义是什么?

跟随代码的区别是什么?

#define MAKE_STRINGS(VAR) #VAR

只有一个#,但前者是两个#

3 个答案:

答案 0 :(得分:2)

它要求预编译器连接两个令牌。

#define DECLARE_DELETE_PTR(type) \
void DeletePtr_##type(string &operand) \
{\
}\

DECLARE_DELETE_PTR(int)会给:

void DeletePtr_int(string &operand)
             //^^^ the macro argument is int, so the precompiler replaces it here
{
}

实际上,在宏代码中,参数type与命令的其余部分连接在一起。如果宏参数是int,那么它只是一个简单的替代,给出了上述结果。请记住,因为它是一个预处理器指令,所以它完全在编译时发生。

如果您使用的是Linux,我建议您查看cpp命令,以便更好地理解。


关于你的第二个问题,区别在于它只是两个不同的运算符。

顾名思义 - >它将其参数转换为c-string(我刚试过)。例如:

std::cout << MAKE_STRINGS(Hello World) << std::endl;

会变成:

std::cout << "Hello World" << std::endl

或者,更有趣的是:

std::cout << MAKE_STRINGS("Hello" World) << std::endl;

变为:

std::cout << "\"Hello\" World" << std::endl;

看起来它也会照顾逃避特殊角色,但我可能错了 - 这来自3分钟前的实验。

答案 1 :(得分:2)

它连接您通过参数type ...

传递的值
DECLARE_DELETE_PTR(gremlin)

将扩展为:

void DeletePtr_gremlin(string &operand)
{
}

答案 2 :(得分:2)

##运算符用于连接两个标记。这是一个例子:

DECLARE_DELETE_PTR(MyType) 

//将扩展为

void DeletePtr_MyType(string &operand)
{
}
相关问题