带内存的 C++ 宏

标签 c++ boost c-preprocessor

这最初是作为对 c++ macros with memory? 的回答发布的

但不知何故我无法编译它。我可能在这里遗漏了一些东西。 (我有一种感觉,这是C++可以做到的事情)

主要.cpp

#include <iostream>
using namespace std;

const char * hello = "hello";
const char * world = "world";

#define VAR

#define MEMORIZE world
#include "memorize.h"
#define MEMORIZE hello
#include "memorize.h"

int main() {
    cout << VAR << endl;
    return 0;
}

内存.h

#undef VAR
#ifndef MEMORIZE
    # error "No Argument to memorize.h"
#endif
#define VAR MEMORIZE
#undef MEMORIZE

我得到的编译错误是这样的:

[100%] Building CXX object CMakeFiles/main.dir/main.cpp.o
error: use of undeclared identifier 'MEMORIZE'
    cout << VAR << endl;
            ^
note: instantiated from:
#define VAR MEMORIZE
            ^
1 error generated.
make[2]: *** [CMakeFiles/main.dir/main.cpp.o] Error 1
make[1]: *** [CMakeFiles/main.dir/all] Error 2
make: *** [all] Error 2

我真的想让这个内存在预处理阶段工作。有人可以帮忙吗?我认为 1.49 中的 BOOST_PP_COUNTER 也使用了这种技术,但我不知道如何使用。

最佳答案

您只使用了一个 VAR 值(最后一个),因为它只能采用一个值。如果您想根据上下文通过 VAR 表达不同的意思,您需要在每个包含之后都有源语句。

#define xstr(a) str(a)
#define str(a) #a
int main() {
#define MEMORIZE world
#include "memorize.h"
      cout << VAR << endl;
#undef MEMORIZE
#define MEMORIZE hello
#include "memorize.h"
      cout << VAR << endl;
          return 0;
}

内存.h:

#undef VAR
#ifndef MEMORIZE
    # error "No Argument to memorize.h"
#endif
#define VAR xstr(MEMORIZE)

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

相关文章:

c++ - 用另一个初始化的静态变量

c++ - 指向不同方法的 vector

c++ - 如何获取两个 boost ptime 之间的每个单独日期

编译时的 C++ 类型检查

c++ - "#define"和 inline 的行为是否相同?

c++ - 从字体名称获取TrueType字体 "post"表

c++ - 为什么克隆方法总是返回一个指针?

c++ - 通过取消引用的基类指针 boost 序列化

c - C 中的 "private header"是什么?

c - C/C++ 预处理器中是否有将字符串转换为数字的指令?