C++,模板化指向函数的指针
C++, templatize pointer to a function
有两个指向不同函数的指针
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 中bind
是boost::bind
,_1
在标头提供的匿名命名空间中。在这种情况下,f
需要接受任何参数,因为bind
的返回类型是具有适当operator()
的未指定类类型。
你当然可以写一个模板,至少在 C++11 中:
template <typename ...Args>
double f(double(*fp)(Args...))
{
double res = fp( /* ??? */ );
}
问题是:你怎么知道如何调用函数?
相关文章:
- QMetaObject invokeMethod的基于函数指针的语法
- C++-试图将函数指针推回到另一个CPP文件中的矢量时出错
- c++r值引用应用于函数指针
- 模板函数指针和lambda
- 是否可以将llvm::FunctionType转换为C/C++原始函数指针
- 带有类的函数指针
- () 函子后面的括号,而不是函数指针?
- 全局作用域中函数指针的赋值
- 使用"Task"函数指针队列定义作业管理器
- 将成员函数指针作为参数传递给模板方法
- 如何创建对象函数指针C++映射?
- 匹配函数指针作为模板参数?
- 通过函数指针定义类范围之外的方法
- 存储在类中的函数指针
- C++从函数指针数组调用函数
- 将返回值存储在函数指针数组的指针中是如何工作的?
- 整数键映射到头文件中的成员函数指针
- 从类成员函数到类 C 函数指针的转换
- 如何将内联匿名函数分配给C++函数指针
- 将字符缓冲区强制转换为函数指针