Population Xplosive
Population Xplosive

Reputation: 617

Different types of functions as arguments in C++

I am writing a program where I need to use different functions for different cases and I need to use these functions extensively. So, I was thinking that the best way to do that is to pass functions as arguments. Both are double functions. However, the number of arguments needed for each function is different. How should I do that? I give a basic scenario of the program below.

if (A > B){
func(double x, double y, double func_A(double a1, double a2));
}else{
func(double x, double y, double func_B(double b1, double b2, double b3));
}

Upvotes: 1

Views: 858

Answers (3)

Tony Delroy
Tony Delroy

Reputation: 106096

One easy way to do this is to have overloads of func call a simple implementation function that accepts separate pointers to double(double, double) and double(double, double, double), the inapplicable one will be NULL...

void func_impl(double x, double y, double (*f)(double, double), double (*g)(double, double, double))
{
    ...
    if (...)
         f(a, b);
    else
         g(a, b, c);
    ...
}

void func(double x, double y, double (*f)(double, double))
{
    func_impl(x, y, f, NULL);
}

void func(double x, double y, double (*g)(double, double, double))
{
    func_impl(x, y, NULL, g);
}

void caller(...)
{
    ...
    if (A > B)
        func(x, y, func_A);
    else
        func(x, y, func_B);
} 

Upvotes: 0

neel
neel

Reputation: 9061

Function overloading is allowed in C++, so just use it. Luchian Grigore has given you an example

Upvotes: 0

Luchian Grigore
Luchian Grigore

Reputation: 258598

You can overload the function func to take different callbacks as parameters:

double func_A(double a1, double a2)
{
    return 0;
}
double func_B(double a1, double a2, double a3)
{
    return 0;
}

typedef double (*FUNCA)(double,double);
typedef double (*FUNCB)(double,double,double);

void func(double x, double y, FUNCA)
{
}
void func(double x, double y, FUNCB)
{
}

int main()
{
    func(0,0,func_A); //calls first overload
    func(0,0,func_B); //calls second overload
}

Upvotes: 4

Related Questions