gpt4 book ai didi

带内存的 C++ 宏

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:19:25 26 4
gpt4 key购买 nike

这最初是作为对 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/

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