gpt4 book ai didi

用于创建字符串数组的 C++ 宏

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

有没有办法用预处理器宏创建一个std::string(或char*)数组?

像这样:

std::string myStrings[] = {MAGIC_MACRO(a, b, c)};

结果:

std::string myStrings[] = {"a", "b", "c"}

我知道它看起来毫无意义,但我需要在具有可变数量参数的更复杂的宏中使用它

最佳答案

下面的代码使用最多 1024 个参数来满足您的要求,并且没有使用额外的东西,比如 boost。它定义了一个 EVAL(...) 和一个 MAP(m, first, ...) 宏来进行递归并在每次迭代中使用宏 m 与下一个参数 first

使用它,您的 MAGIC_MACRO(...) 看起来像:#define MAGIC_MACRO(...) EVAL(MAP(STRINGIZE, __VA_ARGS__)) .

大部分抄自C Pre-Processor Magic .那里也有很好的解释。您还可以在此 git repository 下载这些辅助宏,例如 EVAL(...) ,实际代码中也有很多解释。它是可变的,所以它需要你想要的参数数量。

但是我更改了 FIRSTSECOND 宏,因为它使用了 Gnu 扩展,就像我从中复制它的源代码中一样。

主要功能部分:

int main()
{
std::string myStrings[] = { MAGIC_MACRO(a, b, c) }; // Expands to: std::string myStrings[] = { "a" , "b" , "c" };
std::string myStrings[] = { MAGIC_MACRO(a, b, c, x, y, z) }; // Expands to: std::string myStrings[] = { "a" , "b" , "c", "x" , "y" , "z" };
}

宏定义:

#define FIRST_(a, ...) a
#define SECOND_(a, b, ...) b

#define FIRST(...) FIRST_(__VA_ARGS__,)
#define SECOND(...) SECOND_(__VA_ARGS__,)

#define EMPTY()

#define EVAL(...) EVAL1024(__VA_ARGS__)
#define EVAL1024(...) EVAL512(EVAL512(__VA_ARGS__))
#define EVAL512(...) EVAL256(EVAL256(__VA_ARGS__))
#define EVAL256(...) EVAL128(EVAL128(__VA_ARGS__))
#define EVAL128(...) EVAL64(EVAL64(__VA_ARGS__))
#define EVAL64(...) EVAL32(EVAL32(__VA_ARGS__))
#define EVAL32(...) EVAL16(EVAL16(__VA_ARGS__))
#define EVAL16(...) EVAL8(EVAL8(__VA_ARGS__))
#define EVAL8(...) EVAL4(EVAL4(__VA_ARGS__))
#define EVAL4(...) EVAL2(EVAL2(__VA_ARGS__))
#define EVAL2(...) EVAL1(EVAL1(__VA_ARGS__))
#define EVAL1(...) __VA_ARGS__

#define DEFER1(m) m EMPTY()
#define DEFER2(m) m EMPTY EMPTY()()

#define IS_PROBE(...) SECOND(__VA_ARGS__, 0)
#define PROBE() ~, 1

#define CAT(a,b) a ## b

#define NOT(x) IS_PROBE(CAT(_NOT_, x))
#define _NOT_0 PROBE()

#define BOOL(x) NOT(NOT(x))

#define IF_ELSE(condition) _IF_ELSE(BOOL(condition))
#define _IF_ELSE(condition) CAT(_IF_, condition)

#define _IF_1(...) __VA_ARGS__ _IF_1_ELSE
#define _IF_0(...) _IF_0_ELSE

#define _IF_1_ELSE(...)
#define _IF_0_ELSE(...) __VA_ARGS__

#define COMMA ,

#define HAS_ARGS(...) BOOL(FIRST(_END_OF_ARGUMENTS_ __VA_ARGS__)())
#define _END_OF_ARGUMENTS_() 0

#define MAP(m, first, ...) \
m(first) \
IF_ELSE(HAS_ARGS(__VA_ARGS__))( \
COMMA DEFER2(_MAP)()(m, __VA_ARGS__) \
)( \
/* Do nothing, just terminate */ \
)
#define _MAP() MAP

#define STRINGIZE(x) #x
#define MAGIC_MACRO(...) EVAL(MAP(STRINGIZE, __VA_ARGS__))

关于用于创建字符串数组的 C++ 宏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44303189/

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