C++,模板化指向函数的指针

C++, templatize pointer to a function

本文关键字:函数 指针 C++      更新时间:2023-10-16

有两个指向不同函数的指针

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 cycle)。

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

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

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

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

感谢您的帮助...

可以接受任何东西的方法,作为特例,也可以接受函数指针。 例如

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))

(在 C++11 中,bind std::bind_1 std::placeholders::_1 ,在 Boost 中bindboost::bind_1 在标头提供的匿名命名空间中。在这种情况下,f需要接受任何参数,因为bind的返回类型是具有适当operator()的未指定类类型。

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

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

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