简体   繁体   中英

How to use std::invoke_result_t to get return type of a function

I'm trying to implement a flavored for_each() , it will stop iteration when the passed in function returns false . If the passed in function doesn't return a Boolean value, then run through as std::for_each() .

I'm having some difficulty getting the returned type of function parameter, I tried to use std::invoke_result_t , but it complains:

no member named 'type' in 'std::__1::invoke_result<...

In the example on C++ reference, it always passes in the Arg type for the function. But in my case, shouldn't type F already contain all the type information of the whole function?

template<class C, class F>
void for_each(C container, F&& f)
{
    for (auto const& v : container)
    {
        if constexpr (std::is_same_v<std::invoke_result_t<F>, bool>)
        {
            if (not std::forward<F>(f)(v))
                break;
        }
        else
        {
            std::forward<F>(f)(v);
        }
    }
}

The answer to the first part of the question of "how to make it work" is to include the argument type(s) - in this case, probably something like std::invoke_result_t<F, decltype(v)> .

As for "shouldn't type F already contain all the type information of the whole function?" - as another commenter mentioned, it's possible for F to be a function object with multiple operator() overloads, so the answer is no.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM