Home > Enterprise >  How to pass a function with parameter pack to a function with parameter pack
How to pass a function with parameter pack to a function with parameter pack

Time:05-10

I'm working on a C 14 project and I don't know how to pass a function with parameter pack to another with parameter pack.

template <typename F, typename... Args, typename Callback, typename ... Args2>
bool doAsyncRpc(F func,
                Callback callback, 
                const char* routeType,
                Args&&... args, Args2&&... args2) {
    Request req;
    SetReqValue(&req, std::forward<Args>(args)...);
    func(routeType, req, callback, std::forward<Args2>(args2)...);
    return true;
}

As you see, func is called in the function doAsyncRpc. args is used to initialize the parameter req, callback and args2 are used to pass the func.

Callback is a function and Args2 is its parameters.

It's kind of complicated...

In a word, I don't know how to design the function doAsyncRpc so that it could accept two functions with parameter packs.

CodePudding user response:

You can't deduce two packs from the arguments to a call, so you'll have to wrap at least Args... in a tuple, but it's probably easier to do both.

You then need to shove your other arguments into tuples with those.

template <typename F, typename... Args, typename Callback, typename ... Args2>
bool doAsyncRpc(F func,
                Callback callback, 
                const char* routeType,
                std::tuple<Args&&...> args, 
                std::tuple<Args2&&...> args2) {
    Request req;
    std::apply(SetReqValue, std::tuple_cat(std::make_tuple(&req), args));
    std::apply(func, std::tuple_cat(std::make_tuple(routeType, req, callback), args2));
    return true;
}
  • Related