编写一个模板函数,用于计算具有任何返回类型的 lambda 函数
Writing a template function that evaluates a lambda function with any return type?
我想编写一个'评估'函数,该函数将一个未指定返回类型的函数作为输入,该函数采用一个整数,以及一个整数来调用该函数。
我想出的如下:
#include <functional>
template<typename T>
T eval(function<T(int)> f, int x) {
return f(x);
}
假设我有一个auto func = [] (int x) -> long { return (long)x * x; }
,我想使用上面的函数进行评估。我之前使用模板函数的方式是简单地像调用任何其他函数一样调用它,并让编译器推断类型。
但是,这不适用于此eval
函数。 eval<long>(func, 5)
编译和工作正常,但eval(func, 5)
不能:
Aufgaben10.5.cpp:23:25: error: no matching function for call to 'eval(main()::__lambda0&, int)'
cout << eval(func, 5) << endl;
^
Aufgaben10.5.cpp:23:25: note: candidate is:
Aufgaben10.5.cpp:8:3: note: template<class T> T eval(std::function<T(int)>, int)
T eval(function<T(int)> f, int x) {
^
Aufgaben10.5.cpp:8:3: note: template argument deduction/substitution failed:
Aufgaben10.5.cpp:23:25: note: 'main()::__lambda0' is not derived from 'std::function<T(int)>'
cout << eval(func, 5) << endl;
有没有办法编写一个与 lambda 函数具有相同返回类型的模板函数,而无需将类型显式传递给模板,以便我可以简单地调用 eval(func, 5)
?
为什么不使用decltype
?
template<typename Function>
auto eval(Function&& f, int x) -> decltype(std::forward<Function>(f)(x))
{
return std::forward<Function>(f)(x);
}
相关文章:
- 递归函数计算序列中的平方和(并输出过程)
- 函数计算用户按下按钮的频率
- C++ 在编译时具有函数计算全局变量
- C++ - 使用特定函数计算 x 和 y 的最终值
- 尝试使用函数计算有剩余球员的球队数量
- 我正在尝试创建一个布尔函数,该函数计算字符并在字符为"()*-+"时返回 true
- 哈希函数计算
- 为什么 if 语句对于运算符重载函数计算 false
- 使用C 中的内在函数计算相交
- 如何使用 2 个迭代器进行求和函数计算映射<字符串、双精度>
- vector.size() 函数计算量大吗?
- 如何使用opencv函数计算图像的孔数(二进制)
- 斐波那契函数计算不正确
- 如何用3个用户定义的函数计算一个数字的真平方根
- 元函数计算 x^n 并返回整数限制而不溢出(如果不可能)
- 使用递归函数计算字符串中的元音
- 如何使用 pow() 函数计算 C++ 中超过 2^32 的幂
- 返回 void 的函数的无序函数计算
- 在 C++ 中使用尾递归函数计算列表的总和
- 使用结构和函数计算线的长度