【问题标题】:Writing a template function that evaluates a lambda function with any return type?编写一个模板函数来评估具有任何返回类型的 lambda 函数?
【发布时间】:2014-12-16 11:38:24
【问题描述】:

我想编写一个“评估”函数,该函数将一个未指定返回类型的函数作为输入,该函数接受一个整数,以及一个用于调用该函数的整数。

我想出的是以下内容:

#include <functional>
template<typename T>
T eval(function<T(int)> f, int x) {
    return f(x);
}

假设我有一个auto func = [] (int x) -&gt; long { return (long)x * x; },我想使用上述函数对其进行评估。我之前使用模板函数的方式是像调用任何其他函数一样简单地调用它,并让编译器推断出类型。

但是,这不适用于 eval 函数。 eval&lt;long&gt;(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)

【问题讨论】:

标签: c++ templates c++11 lambda


【解决方案1】:

为什么不使用decltype

template<typename Function>
auto eval(Function&& f, int x) -> decltype(std::forward<Function>(f)(x))
{
   return std::forward<Function>(f)(x);
}

【讨论】:

  • 我会通过&amp;&amp; 接受Function。否则,是的,+1。
  • 因为我不知道。谢谢! :)
  • 不仅没必要;如果是不可复制的函数对象,则根本禁止使用。
  • 如果您要通过&amp;&amp; 获取Function,则应将其称为std::forward&lt;Function&gt;(f)(x),以防它符合参考标准。
  • f 的右值和左值限定调用运算符可能返回不同的类型。返回类型应该是decltype(std::forward&lt;F&gt;(f)(x))
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多