gpt4 book ai didi

c++ - C语言中#define和#if可以嵌套吗?

转载 作者:行者123 更新时间:2023-11-30 19:59:25 24 4
gpt4 key购买 nike

我想编写以下代码,但无法编译。

(核心代码段)

void g();

#define MACRO(x) \
#if (x == 0) \
g(); \
#else \
h(); \
#endif

MACRO(0)

我认为原因可能是#if和#else必须放在不同的行,而#define语句只能有一行。我不知道如何修复代码。谁能帮我?非常感谢!

更新:当我想要导出一组函数时,会出现此问题,每个函数都有一个或多个内部实现。根据参数,所有实现都可能具有最佳性能。请参阅下面的代码。

void fun_1_algo_1(int x);
void fun_1_algo_2(int x);
void fun_2_algo_1(int x);
void fun_2_algo_2(int x);
// fun_1 and fun_2 both have two implementations.
// If x > 1, algo_1 is faster; otherwise algo_2 is faster
void fun_3_aogo_1(int x);
void fun_4_aogo_1(int x);

#define CHECK(x) .... //check if x is a legal number

#define Export(i) \
void fun_##i(int x) { \
CHECK(x); \
#if (i >= 1 && i <= 2) \
if (x > 1) fun_##i##_algo_1(x); \
else fun_##i##_algo_2(x); \
#else \
fun_##i##_algo_1(x); \
#endif \
}

Export(1)
Export(2)
Export(3)
Export(4)

在此示例中,我无法将 #if 更改为 if,因为 fun_3_algo_2(x) 未定义。导出的函数将用作库。

最佳答案

不,你不能那样做。不过,您可以使用模板来近似解决方案。

// generic template to call h() for all values of x
template<uint32_t x>
struct func_chooser {
static inline void f()
{ h(); }
};

// specialise for the zero case (calls g())
template<>
struct func_chooser<0> {
static inline void f()
{ g(); }
};

// the macro just defers to the template
#define MACRO(x) \
func_chooser<x>::f();

关于c++ - C语言中#define和#if可以嵌套吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59960554/

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