Call function with part of variadic arguments

前端 未结 4 754
傲寒
傲寒 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:25

    First, we need a function to retrieve the number or arguments the function requires. This is done using function_traits:

    template 
    constexpr std::size_t nb_args() {
       return utils::function_traits::arity;
    }
    

    And with the help of std::index_sequence, we only dispatch the nb_args() first arguments:

    template
    void foo_impl(F && f, std::index_sequence, Tup && tup) {
        std::forward(f)( std::get(tup)... );
    }
    
    template
    void foo(F && f, Args&&... args) {
        foo_impl(std::forward(f),
                 std::make_index_sequence()>{},
                 std::forward_as_tuple(args...) );
    }
    

    Demo

提交回复
热议问题