C ++ 11/14 INVOKE解决方法 [英] C++11/14 INVOKE workaround

查看:141
本文介绍了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解决方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆