![](/img/trans.png)
[英]C++: How can one get return type of a class member function using std::invoke_result_t?
[英]How to use std::invoke_result_t to get return type of a function
我正在尝试实现风味的for_each()
,当传入的函数返回false
时,它将停止迭代。 如果传入的函数未返回布尔值, std::for_each()
。
我在获取返回的函数参数类型时遇到一些困难,我尝试使用std::invoke_result_t
,但是它抱怨:
在'std :: __ 1 :: invoke_result <...中没有名为'type'的成员
在C ++参考上的示例中 ,它始终为函数传递Arg
类型。 但是就我而言,类型F
是否应该已经不包含整个函数的所有类型信息?
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);
}
}
}
关于“如何使其工作”问题的第一部分的答案是包括参数类型-在这种情况下,可能类似于std::invoke_result_t<F, decltype(v)>
。
至于“类型F是否应该已经包含整个函数的所有类型信息?” -正如另一位评论者所述, F
可能是一个具有多个operator()
重载的函数对象,因此答案是否定的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.