gpt4 book ai didi

C++ 泛型编程的精妙之处

转载 作者:太空狗 更新时间:2023-10-29 23:37:39 24 4
gpt4 key购买 nike

下面的代码说明了我遇到的问题。

#include <iostream>

#define X 4

int main()
{

std::cout << "should be 4: " << X << std::endl;
#define Y X + 4
std::cout << "should be 8: " << Y << std::endl;

#undef Y
#define Y X+0
#undef X
#define X Y+1

std::cout << "expecting 5: " << X << std::endl;
}

错误:

test2.cc: In function ‘int main()’:
test2.cc:17: error: ‘X’ was not declared in this scope

我试图模仿的模式是在代码/构建级别扩展程序(很像 nginx 模块是 wired up at compile-time 的方式)。我需要建立一个可扩展的编译时结构,通过将 #include 添加到我的构建中,该结构是可扩展的(可插入的),这会产生一个具有唯一名称的 boost-mpl-vector,其中包含所有我的插件。因此,如果 X 是唯一的结束名称,则 X_0、X_1、X_2 是在 vector 应用 mpl-vector push_back 的过程中建立的名称。

知道 boost::preprocessor 的抽象是关键,但我还不想花时间研究它,因为我正在制作最终将成为系统原型(prototype)的部分编译时模块化。

所以,为了将来引用,

  1. 为什么我会收到上面的错误?
  2. 正确的原始预处理器模式应该是什么样的。
  3. 正确的 boost-preprocessor-library 模式是什么样的。

最佳答案

用 g++ -E 编译得到:

int main()
{

std::cout << "should be 4: " << 4 << std::endl;

std::cout << "should be 8: " << 4 + 4 << std::endl;






std::cout << "expecting 5: " << X+0 +1 << std::endl;
}

这样您就可以了解为什么会出现错误。

关于C++ 泛型编程的精妙之处,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5592847/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com