有没有更简单的方法来执行宏以定义具有可变数量参数的函数? [英] Is there an easier way to do a macro to define a function with variable amount of arguments?

查看:131
本文介绍了有没有更简单的方法来执行宏以定义具有可变数量参数的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个宏,该宏定义了具有可变数量参数的函数,该宏具有确定必须调用哪个实函数的逻辑.我目前的方法如下:

#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__

我这样使用它:

class AClass : public AInterface {
public:
    FUNC(int,PARAM(int a, int b),PARAM(a,b))
};

我想知道是否有更好的方法可以做到这一点.

注意:声明的函数(在我的示例中为my_func)将用于重新实现超类中的方法,因此使用模板的方法(我所知道的方法)将无法解决我的问题.

Edit2:即使使用适当的可变参数模板化函数,我仍然需要宏来声明该函数,因为它会覆盖超类中的一个函数.

#define FUNC(ret,args,args_call) \
ret my_func(args) { \
    return proper_variadic_templated_function<ret>(args_call);\
}

解决方案

如果我们使用前两个代码块中的EVAL,helper和Conditional宏 解决方案

If we use the EVAL, helper, and Conditional macros from the first two code blocks here. 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.

这篇关于有没有更简单的方法来执行宏以定义具有可变数量参数的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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