Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++11/14 INVOKE workaround

Tags:

c++

c++11

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

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

like image 637
Zizheng Tai Avatar asked Jul 10 '16 02:07

Zizheng Tai


1 Answers

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.

like image 62
T.C. Avatar answered Oct 11 '22 21:10

T.C.