简体   繁体   中英

function pointer member variable

I have a member variable in a class of type double ( )(double) but there are some functions id like to store that have a 2nd default parameter so they're double ( )(double, double) so I can't store it in my current member variable.

Is it possible for me to make my member variable a double ( )(double, double) so it could also store a ( )(double)? Is there any different approach that could accomplish what I want? Or would I need 2 different variables for the case where its using 2 parameters vs 1?

You need two variables. The number of arguments in the call has to match the number of arguments in the function pointer variable, so you can't use the same variable for a different number of arguments.

If you only need one of them at a time, you can save space in the structure by using a union.

double somefunc(double);
double otherfunc(double, double);

struct mystruct {
    union {
        double(*onearg)(double);
        double(*twoarg)(double, double);
    } func
    // other members
};

mystruct obj;

obj.func.onearg = somefunc;
double foo = obj.func.onearg(1.2);
obj.func.twoarg = otherfunc;
double bar = obj.func.twoarg(2.5, 11.1);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM