编写一个模板函数,用于计算具有任何返回类型的 lambda 函数

Writing a template function that evaluates a lambda function with any return type?

本文关键字:函数 计算 用于 任何 lambda 返回类型 一个      更新时间:2023-10-16

我想编写一个'评估'函数,该函数将一个未指定返回类型的函数作为输入,该函数采用一个整数,以及一个整数来调用该函数。

我想出的如下:

#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);
}