如何获取return类型的模板参数方法?

How to get return type of template parameter method?

我正在尝试制作一个模板 class,该模板需要一个 lambda 作为输入,存储它,并将 lambda type = return type 的一些元素存储在 vector 中。但我不知道如何获得该类型,即使在构建实例时,lambda 也以其 return 类型为人所知。

我希望在不提供模板参数的情况下构建 class(如 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 需要一个实际的调用表达式来获取 return 类型,你不能真正可靠地从类型 F 中获取它(因为类型 F例如,可能不是默认可构造的。

您必须使用 std::declval 来“创建”您随后可以调用的 F 实例。

也许像

using value_t = decltype(declval<F>()(0.0));