递归 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屋!