Call function with part of variadic arguments

前端 未结 4 750
傲寒
傲寒 2021-01-22 10:42

Consider I have the following:

void bar(int a, int b)
{
}   

template
void foo(F function, Args... args>
{
    function(a         


        
4条回答
  •  情歌与酒
    2021-01-22 11:12

    Here is a solution that will work with anything std::invoke accepts, that invokes the overload with the fewest possible arguments.

    template 
    decltype(auto) invoke_front_impl(F&& f, Args&& args, std::index_sequence)
    {
        if constexpr (std::is_invocable_v...>) {
            return std::invoke(std::forward(f), std::get(std::move(args))...);
        } else {
            return invoke_front_impl(
                std::forward(f),
                std::move(args),
                std::make_index_sequence());
        }
    }
    
    template 
    decltype(auto) invoke_front(F&& f, Args&&... args)
    {
        return invoke_front_impl(
            std::forward(f),
            std::forward_as_tuple(std::forward(args)...),
            std::make_index_sequence<0>());
    }
    

    Demo on Wandbox

提交回复
热议问题