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

问题描述

我正在尝试制作一个模板类,它需要一个 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));