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

What's the meaning of ## in the define code in C++

本文关键字:是什么 代码 C++ 定义      更新时间:2023-10-16
#define DECLARE_DELETE_PTR(type) 
void DeletePtr_##type(string &operand) 
{
}

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

与后面的代码有什么不同?

#define MAKE_STRINGS(VAR) #VAR

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

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

#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分钟前的实验

它将您通过参数type传递的值连接在一起…

DECLARE_DELETE_PTR(gremlin)

展开为:

void DeletePtr_gremlin(string &operand)
{
}

##操作符用于连接两个令牌。下面是一个例子:

DECLARE_DELETE_PTR(MyType) 

//展开为

void DeletePtr_MyType(string &operand)
{
}