如何正确找出lambda的返回类型 [英] how to correctly find out the return type of a lambda

查看:118
本文介绍了如何正确找出lambda的返回类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

basically how to make following code compile?

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

I know it failed because compiler was trying to evaluate something like ([](int &i){})(0) but how to solve the problem?

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

}


推荐答案

您可以使用以下特征:

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;
};

这篇关于如何正确找出lambda的返回类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆