我正在尝试制作一个期望lambda作为输入的模板类,将其存储,还存储在lambda的vector
某些元素中type = return type
。但我不知道如何获取该类型,即使在构建实例时也知道lambda及其返回类型。
我希望在不提供模板参数(例如std::array a{1, 2, 3}
)的情况下构造该类。我尝试过,decltype(F::operator(double x))
但没有用。
#include <vector>
template<typename F>
struct Foo {
using value_t = decltype(F::operator(double x))// <--- here I need to get the return type of the
// call operator of F!
Foo(const F& f) : _f(f), _vals(10, value_t{}), _has_vals(10, false) {}
value_t operator()(int i) {
if (_has_vals[i])
return _vals[i];
else {
_has_vals[i] = true;
_vals[i] = _f(i);
}
}
F _f;
std::vector<value_t> _vals;
std::vector<bool> _has_vals;
};
#include <iostream>
int main() {
Foo foo([](double x){ return 42; }); // <--- here I know that the lambda returns an int!
std::cout << foo(3) << "\n";
return 0;
};
decltype
需要一个实际的调用表达式来获取返回类型,您不能真正可靠地从该类型中获取该返回类型F
(例如,因为该类型F
可能不是默认可构造的)。
您必须使用std::declval
“创建”F
您可以调用的实例。
也许像
using value_t = decltype(declval<F>()(0.0));
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句