C ++需要一个容器来存储用户定义的函数 [英] C++ need a container to store user defined function
问题描述
我正在尝试在用户定义的函数和数据之间创建一个接口。假设我需要创建一个名为 MapFun()
的函数, MapFun()
的输入包含用户定义的函数(UDF )处理和UDF输入。
I am trying to create a interface between user defined function and data. Let's say I need to create a function called MapFun()
, input of MapFun()
includes user defined function (UDF) handle and UDF inputs.
void userFun1(Data data, int in1, int in2){
// user defined function 1;
}
void userFun2(Data data, int in1, int in2, std::string s){
// user defined function 2;
}
// ...
// apply user function 1 on data
MapFun(@userFun1, data, 3, 4);
// apply user function 2 on data
MapFun(@userFun2, data, 1, 2, "algorithm");
用户将写入 userFun
并应用 MapFun()
。那么,如何设计 MapFun()
?用户功能可能有不同的输入,并且无法预测签名。此外, MapFun()
不会立即评估 userFun
,而是存储所有 userFun
并进行懒惰的评估。
User will write userFun
and apply it with MapFun()
. So, how to design MapFun()
? User function may have different inputs and the signature can't be predicted. In addition, MapFun()
won't evaluate userFun
immediately, instead, it stores all userFun
and do a lazy evaluation.
任何建议都将不胜感激。
Any suggestions are greatly appreciated.
推荐答案
用户功能可能具有不同的输入,并且无法预测签名。
User function may have different inputs and the signature can't be predicted.
看来是可变参数模板的典型作品
It seems a typical works for variadic templates
此外,
MapFun()
不会立即评估userFun
,而是存储所有userFun
并做一个懒惰的评估。
In addition,
MapFun()
won't evaluateuserFun
immediately, instead, it stores alluserFun
and do a lazy evaluation.
不确定,但我想您可以得到什么我想使用 std :: bind()
,或者更好地使用lambda函数。
Not sure to understand but I suppose you can obtain what do you want using std::bind()
or, maybe better, with lambda functions.
我建议使用以下C ++ 14可变参数模板 MapFun()
函数,该函数返回同时捕获用户函数和参数的lambda函数。该函数可以在以后执行。
I propose the following C++14 variadic template MapFun()
function that return a lambda function that capture both user-function and argument. That function can be executed later.
template <typename F, typename ... Args>
auto MapFun (F const & f, Args const & ... args)
{ return [=]{ f(args...); }; }
以下是完整的示例
#include <iostream>
template <typename F, typename ... Args>
auto MapFun (F const & f, Args const & ... args)
{ return [=]{ f(args...); }; }
void userFun1 (int i1, int i2)
{ std::cout << "uf1, " << i1 << ", " << i2 << std::endl; }
void userFun2 (int i1, int i2, std::string const & s)
{ std::cout << "uf2, " << i1 << ", " << i2 << ", " << s << std::endl; }
int main ()
{
auto l1 = MapFun(userFun1, 1, 2);
auto l2 = MapFun(userFun2, 3, 4, "five");
l2();
l1();
}
这篇关于C ++需要一个容器来存储用户定义的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!