如何在 C++ 中检索先前声明的变量并在其名称中粘贴 __COUNTER__?

How to retrieve a previously declared variable with __COUNTER__ pasted inside its name in C++?

我有以下问题:

#define CONCAT_(A,B) A ## B
#define CONCAT(A,B) CONCAT_(A,B)
#define CREATE_NAME(N) CONCAT(N, __COUNTER__)

如果我想在代码后面检索特定的 variable##__COUNTER__,我该如何实现?我只需要得到前一个,比如:

#define CONCAT_(A,B) A ## B
#define CONCAT(A,B) CONCAT_(A,B)
#define CREATE_NAME(N) CONCAT(N, __COUNTER__)
#define GET_NAME_PREV(N, VAL) CONCAT(N, VAL)

auto CREATE_NAME(v);
auto test_current_counter_value = GET_NAME_PREV(v, __COUNTER__ -1);

谢谢。

BOOST_PP_SUB boost 库中的宏可以被评估并扩展为标识符。

#include <boost/preprocessor/arithmetic/sub.hpp>

#define CONCAT_(A,B) A ## B
#define CONCAT(A,B) CONCAT_(A,B)
#define CREATE_NAME(N) CONCAT(N, __COUNTER__)
#define GET_NAME_PREV(N) CONCAT(N, BOOST_PP_SUB(__COUNTER__, 1))

auto CREATE_NAME(v) = true;
auto test_current_counter_value = GET_NAME_PREV(v);

Compiler Explorer 上试用。