[英]Is there an easier way to do a macro to define a function with variable amount of arguments?
I have a macro that defines a function with a variable amount of arguments, the macro has some logic to decide which real function must be called. 我有一个宏,该宏定义了具有可变数量参数的函数,该宏具有确定必须调用哪个实函数的逻辑。 My current approach is the following:
我当前的方法如下:
#define FUNC(ret,args,args_call) \
ret my_func(args) { \
if( something ) other_func(args_call);\
return one_func(args_call);\
}
#define PARAM(...) __VA_ARGS__
I use it like that: 我这样使用它:
class AClass : public AInterface {
public:
FUNC(int,PARAM(int a, int b),PARAM(a,b))
};
I was wondering if there is a better way to do that. 我想知道是否有更好的方法可以做到这一点。
Note: The declared ( my_func
in my example) function will be used to reimplement a method from the super class, so the approaches using templates (the ones that I am aware of) will not solve my problem. 注意:声明的函数(在我的示例中为
my_func
)将用于重新实现超类中的方法,因此使用模板的方法(我知道的方法)将无法解决我的问题。
Edit2: Even using a proper variadic templated function, I still need the macro to declare the function because it overrides a function in the superclass. Edit2:即使使用适当的可变参数模板化函数,我仍然需要宏来声明该函数,因为它会覆盖超类中的函数。
#define FUNC(ret,args,args_call) \
ret my_func(args) { \
return proper_variadic_templated_function<ret>(args_call);\
}
If we use the EVAL
, helper, and Conditional macros from the first two code blocks here . 如果我们在这里使用前两个代码块中的
EVAL
,helper和Conditional宏。 We can create some recursive macros to parse the parameter array. 我们可以创建一些递归宏来解析参数数组。
As the comma is syntactic we will need to escape it for outputting. 由于逗号是句法,我们将需要对其进行转义以进行输出。
#define COMMA() ,
We can generate two functions to separate the types from the names. 我们可以生成两个函数来将类型与名称分开。
#define I_WT_R() I_WT
#define I_WT(t,v,n,...) \
t v IS_DONE(n)( \
EAT \
, \
OBSTRUCT(COMMA)() \
OBSTRUCT(I_WT_R)() \
)(n,__VA_ARGS__)
#define WithTypes(...) I_WT(__VA_ARGS__,DONE)
And. 和。
#define I_WoT_R() I_WoT
#define I_WoT(t,v,n,...) \
v IS_DONE(n)( \
EAT \
, \
OBSTRUCT(COMMA)() \
OBSTRUCT(I_WoT_R)() \
)(n,__VA_ARGS__)
#define WithoutTypes(...) I_WoT(__VA_ARGS__,DONE)
Redefining your macro as such: 重新定义宏,如下所示:
#define FUNC(ret,args) EVAL( \
ret my_func(WithTypes args) { \
if( something ) other_func(WithoutTypes args); \
return one_func(WithoutTypes args); \
})
Allows you the slightly better syntax of: 允许您使用以下更好的语法:
class AClass : public AInterface {
public:
FUNC(int,(int,a,int,b))
};
Compiling to (after adding newlines): 编译为(添加换行符之后):
class AClass : public AInterface {
public:
int my_func(int a , int b ) {
if( something )
other_func(a , b );
return one_func(a , b );
}
};
Hope that helps. 希望能有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.