0

有两个指向不同功能的指针

typedef std::vector<double> TData;
double ( * p_test1 ) ( const TData> &arg);
double ( * p_test2 ) ( const TData> &ar1, char *arg2, char *arg3);

和一个方法,它有一个指向函数的指针作为参数

double f (double ( * p_test1 ) ( const TData  &arg ))
{
    //Long and not trivial algorithm processing results of p_test
    for ( i = 0;... )
    {
       double res = p_test (arg);  //Some computations
    }
}

f() 方法包含困难的计算(这里用 for 循环代替)。

是否可以将此参数模板化(即指向具有不同数量参数的函数的指针)以获得处理两种类型参数的通用函数

double f (double ( * p_test1 ) ( const TData  &arg ));
double f (double ( * p_test2 ) ( const TData> &ar1, char *arg2, char *arg3));

或者有什么方法可以编写这样的函数,例如写一个指向函数指针的指针?

我想避免 f() 函数的部分专业化,因为它很复杂(重复覆盖长代码效率不高)。

谢谢你的帮助...

4

2 回答 2

1

你当然可以写一个模板,至少在 C++11 中:

template <typename ...Args>
double f(double(*fp)(Args...))
{
    double res = fp( /* ??? */ );
}

问题是:你怎么知道如何调用函数?

于 2012-10-05T11:09:09.893 回答
1

作为一种特殊情况,可以采用任何方法的方法也可以采用函数指针。例如

template<typename Function>
double f (Function p_test)
{ ...
    // if p_test is a function pointer or has operator(), this will work
    double res = p_test (arg);
  ... }

然而,问题归结为两个函数采用不同的参数这一事实。因此,参数要么必须以某种方式捆绑到f,要么无论如何都需要有几种不同的实现,或者参数将始终相同。

要捆绑参数,通常的方法是使用std::bind(C++11) 或boost::bind. 假设您有一个需要 3 个参数 ( test2) 的函数,并且需要将其传递给f仅提供第一个参数的通用算法 ()。你知道另外两个。所以你这样做:

f(bind(&test2, _1, secondarg, thirdarg))

(In C++11 bind is std::bind and _1 is std::placeholders::_1, in Boost bind is boost::bind and _1 is in anonymous namespace provided by the header.) In this case f needs to take any argument, because the return type of bind is unspecified class type with appropriate operator().

于 2012-10-05T12:50:57.040 回答