简体   繁体   中英

call member function with expanded tuple parms std::invoke vs std::apply

I found std::invoke to call every callable object with a set of parms and std::apply to expand a tuple as parms to a callable.

Is there a combination of both which enables to invoke any callable with a tuple as parms?

#include <iostream>
#include <tuple>
#include <functional>

class A
{
    private:
        int n;

    public:
        A( int _n ): n(_n){}

        void operator()(int x, double y )
        {
            std::cout << n << " " << x << " " << y << std::endl;
        }

        void MemFun( int x, double y )
        {
            std::cout << n << " " << x << " " << y << std::endl;
        }
};

int main()
{
    A a(100);
    std::invoke( a, 10, 1.23 );

    auto parm2 = std::make_tuple( 1,2.34);
    std::apply ( a, parm2 );

    std::invoke ( &A::MemFun, a, 4, 5.67 );

    // ???
    std::??apply_invoke?? ( &A::MemFun, a, parm2 );
}

Do you mean something like this?

std::apply(&A::MemFun, std::tuple_cat(std::make_tuple(a), parm2));

Is there a combination of both which enables to invoke any callable with a tuple as parms?

std::apply can be used to invoke any callable, so I'm not really understanding the problem here. It's just like std::invoke for member functions: The first parameter needs to be the object you want to call the function on. Same goes for std::apply , where the first element of the passed tuple needs to be the object you want it to be called on.

If you don't like specifying std::tuple_cat and such, you can always create a wrapper:

template<typename F, typename T, typename U>
decltype(auto) apply_invoke(F&& func, T&& first, U&& tuple) {
    return std::apply(std::forward<F>(func), std::tuple_cat(std::forward_as_tuple(std::forward<T>(first)), std::forward<U>(tuple)));
}

How about std::apply( std::bind(&A::MemFun, &a, std::placeholders::_1, std::placeholders::_2), parm2 ); ?

Edited to include suggestions and placeholders

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM