C++ 宏间接

标签 c++

谁能解释一下为什么会这样:

#include <iostream>

using namespace std;

#define cat(a,b) cat_1(a,b) 
#define cat_1(a,b) a ## b
int main()
{
    cat(c,cat(o,cat(u,t))) << "Hello world!";
    return 0;
}

但是少一级宏间接的相同代码不会:

#include <iostream>

using namespace std;

#define cat(a,b) a ## b
int main()
{
    cat(c,cat(o,cat(u,t))) << "Hello world!";
    return 0;
}

我看过这个:

http://www.boost.org/doc/libs/1_55_0/libs/preprocessor/doc/

虽然它说明了问题,但我仍然不明白这是如何解决的。当我在此 (g++ -E) 上运行预处理器时:

#include <iostream>

using namespace std;

#define cat(a,b) cat_1(a,b) 

int main()
{
    cat(c,cat(o,cat(u,t))) << "Hello world!";
    return 0;
}

它将行扩展为:

cat_1(c,cat_1(o,cat_1(u,t))) << "Hello world!"

所以看起来问题应该仍然存在,因为它直接映射到只有'cat'的行

最佳答案

## 运算符在为更多宏调用重新扫描宏替换之前应用。外部调用首先扩展为 ccat(o,cat(u,t)),然后扩展为 ccat(o, ut) 并在那里停止。

额外的间接允许在标记粘贴之前重新扫描。

关于C++ 宏间接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24708006/

相关文章:

c++ - 我的射线三角形交叉点代码正确吗?

C++ SFML 数组错误 : Access violation reading location 0xC0000005

c++ - 如何解决这个总线错误?

C++如何在另一个类中使用运算符重载

c++ - 在 C++17 中,为什么类模板与函数模板的指针类型推导明显不一致?

c++ - Qt QHeaderView::sectionResized 和 QHeaderView::geometriesChanged 没有按预期工作

c++ - fltk1.3 Fl_Image::draw(边界框)

c++ - TEXT() 函数 - 文档在哪里?

c++ - 使用一个参数调用宏

c++ - 当我们在 C++ 中使用 k=k-- 时会发生什么?