编写一个模板函数来评估任何返回类型的lambda函数?

Dav*_*olt 2 c++ lambda templates c++11

我想编写一个'评估'函数,它接受一个带有整数的未指定返回类型的函数作为输入,并使用一个整数来调用该函数.

我想出的是以下内容:

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

假设我有一个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;
Run Code Online (Sandbox Code Playgroud)

有没有办法编写一个模板函数,它具有与lambda函数相同的返回类型,而没有显式地将类型传递给模板,所以我可以简单地调用eval(func, 5)

For*_*veR 8

为什么不用decltype

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

  • 如果你要用`&&'来取'Function`,你应该把它称为`std :: forward <Function>(f)(x)`以防它是ref限定的. (3认同)
  • 我用'&&`取'Function`.否则,那,+ 1. (2认同)