递归C宏未扩展 [英] Recursive C macro not expanded
问题描述
我正在处理一个递归宏.但是,它似乎没有递归扩展.这是一个显示我的意思的最小工作示例:
I am working on a recursive macro. However, it seems that it is not expanded recursively. Here is a minimal working example to show what I mean:
// ignore input, do nothing
#define ignore(...)
// choose between 6 names, depending on arity
#define choose(_1,_2,_3,_4,_5,_6,NAME,...) NAME
// if more than one parameter is given to this macro, then execute f, otherwise ignore
#define ifMore(f,...) choose(__VA_ARGS__,f,f,f,f,f,ignore)(__VA_ARGS__)
// call recursively if there are more parameters
#define recursive(first,args...) first:ifMore(recursive,args)
recursive(a,b,c,d)
// should print: a:b:c:d
// prints: a:recursive(b,c,d)
recursive
宏应以递归方式扩展自身,并始终将结果连接起来,并用冒号分隔.但是,它不起作用.正确生成了递归宏(如结果 a:recursive(b,c,d)
所示,其中再次包含对宏的格式正确的调用),但是生成的递归调用ist不被夸大.
The recursive
macro should expand itself recursively and always concatenate the result, separated with a colon. However, it doesn't work. The recursive macro is generated correctly (as can be seen on the result a:recursive(b,c,d)
which includes a well-formed call to the macro again), but the generated recursive call ist not exanded.
为什么会这样,如何获得想要的行为?
Why is this the case and how can I get the behaviour I want?
推荐答案
您无法获得想要的行为.根据设计,C预处理器尚未完成.
You can't get the behaviour you want. The C preprocessor is, by design, not turing complete.
您可以使用多个宏来获取多个替换项,但是使用任意数量的替换项都无法实现真正的递归.
You can use multiple macros to get multiple replacements, but you will not achieve true recursion with an arbitrary number of replacements.
这篇关于递归C宏未扩展的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!