C++11/14 INVOKE workaround

孤街醉人 提交于 2019-12-10 14:25:41

问题


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)...)();
}

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).


回答1:


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)...);
}

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.)

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.



来源:https://stackoverflow.com/questions/38288042/c11-14-invoke-workaround

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!