如何正确找出lambda的返回类型

Bry*_*hen 3 c++ c++11

基本上如何使以下代码编译?

我知道它失败了,因为编译器试图评估类似的东西,([](int &i){})(0)但是如何解决该问题呢?

template <class TElement>
struct foo {
    TElement _e;
    foo(TElement e) : _e(e){}
    template <class Lambda>
    void bar(Lambda f) {
        using TResult = decltype(std::declval<Lambda>()(std::declval<TElement>()));
    }
};

int main() {

    foo<int>(0).bar([](int i){}); // compile
    foo<int>(0).bar([](int &&i){}); // compile
    foo<int>(0).bar([](int const &i){}); // compile
    foo<int>(0).bar([](int &i){}); // failed

}
Run Code Online (Sandbox Code Playgroud)

Jar*_*d42 5

您可以使用以下特征:

template <typename T>
struct return_type : return_type<decltype(&T::operator())>
{};
// For generic types, directly use the result of the signature of its 'operator()'

template <typename ClassType, typename ReturnType, typename... Args>
struct return_type<ReturnType(ClassType::*)(Args...) const>
{
    using type = ReturnType;
};
Run Code Online (Sandbox Code Playgroud)