C预处理器将"int x"分割为整数.进入int& X [英] C Preprocessor to split "int x" into int & x

查看:99
本文介绍了C预处理器将"int x"分割为整数.进入int& X的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要具备以下条件:

#define MY_MACRO(PARAM1,PARAM2) \
 MY_OTHER_MACRO(TYPENAME_OF(PARAM1),PARAMNAME_OF(PARAM1));\
 MY_OTHER_MACRO(TYPENAME_OF(PARAM2),PARAMNAME_OF(PARAM2));\

引起

MY_MACRO(int x,char *z) 

编译为

MY_OTHER_MACRO(int,x);
MY_OTHER_MACRO(char*,z);

否则编译为:

MY_OTHER_MACRO(int,x);
MY_OTHER_MACRO(char,*z);

甚至也可以:(我可以编码MY_OTHER_MACRO以使用任一结果)

or even this would be ok too: (i can code MY_OTHER_MACRO to work with either result)

MY_OTHER_MACRO(int,x);
MY_OTHER_MACRO(char,z);

或者,如果有某种方法可以计数由空格分隔的令牌(并假设"*"是单独的令牌,那么我也可以使用它-例如2 vs 3) 据我所知,令牌通常用逗号分隔.有什么办法可以使用另一个字符?

alternatively, if there is some way of counting the tokens that are separated by whitespace (and assume that "*" is separate token, i can work with that too - e.g. 2 vs 3) typically, tokens are separated by commas, as far as i know. is there any way to use another character?

推荐答案

您可以执行此操作,但有一个非常困难的限制,即您必须事先知道所有类型名称:它不适用于任何用户-定义的类型,除非用户也将它们添加到已知类型的列表中-这不难.

You can do this, but only with the extremely difficult limitation that you must know all of the type names in advance: it won't work with any user-defined types unless the user adds them to the list of known types too - that's admittedly not hard.

接受此限制,您可以执行以下操作:

Accepting this limitation, you can do something like this:

#define LPAREN (
#define RPAREN )
#define COMMA ,

#define CAT(L, R) CAT_(L, R)
#define CAT_(L, R) L ## R
#define EXPAND(...) __VA_ARGS__

#define SPLIT(OP, D) EXPAND(OP CAT(SPLIT_, D) RPAREN)

#define SPLIT_int LPAREN int COMMA
#define SPLIT_char LPAREN char COMMA
#define SPLIT_float LPAREN float COMMA
#define SPLIT_double LPAREN double COMMA

#define MY_MACRO(A, B) \
SPLIT(MY_OTHER_MACRO, A); SPLIT(MY_OTHER_MACRO, B);

MY_MACRO(int x, char * z)  // emits MY_OTHER_MACRO ( int , x ); MY_OTHER_MACRO ( char , * z );

如上所述,将一种类型添加到已知类型的列表中是一种单行(#define SPLIT_myType LPAREN myType COMMA),并且可以在程序中的任何位置进行,只要它在SPLIT实际使用该类型之前就可以完成. ,尽管它具有很高的侵入性,但它不是世界末日.

Adding a type to the list of known types is, as above, a one-liner (#define SPLIT_myType LPAREN myType COMMA), and can be done anywhere in the program as long as it comes before the type is actually used by SPLIT, so it's not the end of the world, although it is highly intrusive.

没有简单的方法来使星号位于拆分的左侧.可能可以这样做,但要复杂得多,并且涉及对允许的变量名列表进行限制,而IMO则要差得多.也许也更具侵入性,因为在工作程序中几乎可以肯定您拥有比类型更多的变量.

There is no easy way to get the asterisk to be on the left of the split. It could probably be done, but it would be much more complicated, and involve placing the restriction on the list of allowed variable names, which IMO is much, much worse. Probably more intrusive too, since you're almost certain to have more variables than types in a working program.

这篇关于C预处理器将"int x"分割为整数.进入int& X的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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