【发布时间】: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) -> 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)?
【问题讨论】:
-
我将在这里完全摆脱
function,将T&& f传递给eval,并将decltype传递给返回类型。
标签: c++ templates c++11 lambda