how to correctly find out the return type of a lambda

后端 未结 3 1895
闹比i
闹比i 2020-12-11 22:04

basically how to make following code compile?

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

相关标签:
3条回答
  • 2020-12-11 22:30

    Two ways. First:

    using TResult = decltype(f(_e));
    

    or second:

    using TResult = typename std::result_of<Lambda&(TElement&)>::type;
    

    Your code implicity says that the TElement is a temprary/rvalue. The & above makes them lvalues.

    0 讨论(0)
  • 2020-12-11 22:30

    You might resolve it with:

    template <typename Lambda, typename T>
    struct lambda_return_type {
        private:
        template<typename U>
        static constexpr auto check(U*) -> decltype(std::declval<Lambda>()(std::declval<U>()));
    
        template<typename U>
        static constexpr auto check(...) -> decltype(std::declval<Lambda>()(std::declval<U&>()));
    
        public:
        typedef decltype(check<T>(nullptr)) type;
    };
    

    and

    void bar(Lambda f) {
        typedef typename lambda_return_type<Lambda, TElement>::type TResult;
    }
    
    0 讨论(0)
  • 2020-12-11 22:41

    You may use following traits:

    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;
    };
    
    0 讨论(0)
提交回复
热议问题