可变递归预处理器宏 - 有可能吗? [英] Variadic recursive preprocessor macros - is it possible?

查看:17
本文介绍了可变递归预处理器宏 - 有可能吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一点理论问题.在我维护的一段代码中,有一组宏,例如

I've run into a little theoretical problem. In a piece of code I'm maintaining there's a set of macros like

#define MAX_OF_2(a, b)       (a) > (b) ? (a) : (b)
#define MAX_OF_3(a, b, c)    MAX_OF_2(MAX_OF_2(a, b), c)
#define MAX_OF_4(a, b, c, d) MAX_OF_2(MAX_OF_3(a, b, c), d)
...etc up to MAX_OF_8

我想做的是用这样的东西替换它们:

What I'd like to do is replace them with something like this:

/* Base case #1, single input */
#define MAX_OF_N(x)      (x)

/* Base case #2, two inputs */
#define MAX_OF_N(x, y)   (x) > (y) ? (x) : (y)

/* Recursive definition, arbitrary number of inputs */
#define MAX_OF_N(x, ...) MAX_OF_N(x, MAX_OF_N(__VA_ARGS__))

...当然,这不是有效的预处理器代码.

...which, of course, is not valid preprocessor code.

忽略这种特殊情况可能应该使用函数而不是预处理器宏来解决,是否可以定义可变参数 MAX_OF_N() 宏?

Ignoring that this particular case should probably be solved using a function rather than a preprocessor macro, is it possible to define a variadic MAX_OF_N() macro?

为了清楚起见,最终结果应该是一个宏,它接受任意数量的参数并计算出其中最大的一个.我有一种奇怪的感觉,这应该是可能的,但我不知道如何.

Just for clarity, the end result should be a single macro that takes an arbitrary number of parameters and evaluates to the largest of them. I've got an odd feeling that this should be possible, but I'm not seeing how.

推荐答案

不,因为预处理器只对文件进行一次滑动".没有办法让它递归地定义宏.

No, because the preprocessor only takes one "swipe" at the file. There's no way to get it to recursively define macros.

我见过的唯一代码是不是可变参数,而是使用用户必须传递的默认值:

The only code that I've seen do something like this was not variadic, but used default values the user had to pass:

x = MAX_OF_8 (a, b, -1, -1, -1, -1, -1, -1)

假设所有值都是非负数.

assuming all values were non-negative.

内联函数至少应该为 C++ 提供相同的功能.正如您所说,最好留给具有类似于 printf() 的可变参数的函数.

Inline functions should give you the same for C++ at least. As you state, it's probably better left to a function with variable arguments similar to printf().

这篇关于可变递归预处理器宏 - 有可能吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆