带内存的 C++ 宏?

2022-01-11 00:00:00 macros c++

是否可以定义宏

write_foo(A);
and
read_foo();

这样:

WRITE_FOO(hello);

code_block_1;

READ_FOO();

code_block_2;

READ_FOO();

WRITE_FOO(world);

code_block_3;

READ_FOO();

code_block_4;

READ_FOO();

扩展为:

code_block_1;
hello;
code_block_2;
hello;

code_boock_3;
world;
code_block_4;
world;

?

谢谢!

推荐答案

宏不能重新定义其他宏,但是你可以手动完成.

Macros cannot redefine other macros, but you can do it manually.

#define FOO hello

FOO // expands to hello

#undef FOO
#define FOO world

FOO // expands to world

#undef FOO
#define FOO blah

FOO // expands to blah

不幸的是,#define + #undef 组合无法封装在我知道的任何其他结构中.

Unfortunately, the #define + #undef combination cannot be encapsulated in any other structure that I am aware of.

相关文章