C ++ 11/14 INVOKE解决方法

编程入门 行业动态 更新时间:2024-10-25 18:25:47
本文介绍了C ++ 11/14 INVOKE解决方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我需要使用 INVOKE 语义(由C ++ 17中的 std :: invoke 实现)一些C ++ 11/14代码。我当然不想自己实施它,我相信这将是一场灾难。因此,我决定使用现有的标准图书馆设施。很快我想到的是:

I need to use the INVOKE semantics (implemented by std::invoke in C++17) in some C++11/14 code. I certainly don't want to implement it myself, which I believe would be a disaster. So I decided to make use of present standard library facilities. Quickly came to my mind was:

template<typename Fn, typename... Args> constexpr decltype(auto) my_invoke(Fn&& f, Args&&... args) noexcept(noexcept(std::bind(std::forward<Fn>(f), std::forward<Args>(args)...)())) { return std::bind(std::forward<Fn>(f), std::forward<Args>(args)...)(); }

此实现的一个问题是它无法区分左值和右值可调用项(例如,如果函数对象在 operator()()&和 operator()()&& ,则只会调用& 版本)。是否有一些库实用程序也可以完美地转发可调用对象本身?如果没有,什么是实现它的好方法? (例如,转发包装器。)

A problem with this implementation is it can't distinguish between lvalue and rvalue callables (e.g., if a function object overloads on operator()() & and operator()() &&, only the && version would ever be called). Is there some library utility that also perfect forwards the callable itself? If not, what would be a good way to implement it? (A forwarding wrapper, for example).

推荐答案

所有 INVOKE 的特殊情况是关于成员的指针。只需在SFINAE上将其发送到 mem_fn 。

All of INVOKE's special cases are about pointers to members. Just SFINAE on that and ship them to mem_fn.

template<typename Fn, typename... Args, std::enable_if_t<std::is_member_pointer<std::decay_t<Fn>>{}, int> = 0 > constexpr decltype(auto) my_invoke(Fn&& f, Args&&... args) noexcept(noexcept(std::mem_fn(f)(std::forward<Args>(args)...))) { return std::mem_fn(f)(std::forward<Args>(args)...); } template<typename Fn, typename... Args, std::enable_if_t<!std::is_member_pointer<std::decay_t<Fn>>{}, int> = 0> constexpr decltype(auto) my_invoke(Fn&& f, Args&&... args) noexcept(noexcept(std::forward<Fn>(f)(std::forward<Args>(args)...))) { return std::forward<Fn>(f)(std::forward<Args>(args)...); }

这实际上是 N4169 。 (真正的标准库实现者不这样做,因为将INVOKE功能集中在一个地方,而调用它的其他各个部分则更容易维护。)

This is essentially the minimal implementation proposed in N4169. (Real standard library implementers don't do this, because it's much more maintainable to centralize the INVOKE functionality in one place and have various other parts just call into it.)

顺便说一句,使用 std :: bind 是完全错误的。它复制/移动所有参数,将它们作为左值传递给可调用对象,并使用reference_wrappers,占位符和绑定表达式进行不必要的魔术操作。

By the way, using std::bind is completely wrong. It copies/moves all of the arguments, passes them to the callable as lvalues, and does unwanted magic with reference_wrappers, placeholders, and bind expressions.

更多推荐

C ++ 11/14 INVOKE解决方法

本文发布于:2023-11-04 17:41:49,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1558589.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:解决方法   INVOKE

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!