Reputation: 165
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);
}
}
}
Upvotes: 5
Views: 11902
Reputation: 977
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.
Upvotes: 9