[英]Different types of functions as arguments in C++
我正在编写一个程序,我需要为不同的情况使用不同的函数,我需要广泛使用这些函数。 所以,我认为最好的方法是将函数作为参数传递。 两者都是双重功能。 但是,每个函数所需的参数数量是不同的。 我该怎么办? 我给出了以下程序的基本情景。
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));
}
您可以重载函数func
以将不同的回调作为参数:
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
}
在C ++中允许函数重载,所以只需使用它。 Luchian Grigore给了你一个例子
一个简单的方法是让func的重载调用一个简单的实现函数,接受单独的指针指向double(double, double)
和double(double, double, double)
,不适用的指针将为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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.