Search code examples
c++initializer-list

How to put a part of variable argument list into another function?


I'm dealing with such a problem, I have function f(std::initializer_list<double> list),and I want to put a part of variable argument list (the second variable argument to end) into another function like:

void f(std::initializer_list<double> list){
    f1(*(list.begin()+1,...,*(list.end-1));
}

The f1 function is normal function like void f1(double x) or void f1(double x1,double x2), I want f can do with different variable argument number of f1, how can I get it?


Solution

  • An initializer list does not seem to have constructors which take a pair of iterators, see here. But you can use a span for that:

    #include<iostream>
    #include<span>
    
    void f1(double a, double b)
    {
    }
    
    void f2(auto list)
    {
        for(auto i : list)
        {
            std::cout<<i<<std::endl;
        }
    }
    
    void f(std::initializer_list<double> list){
        size_t size = std::distance(std::begin(list),std::end(list))-1;
        auto list = std::span{std::next(std::begin(list)), size};
        f1(list[0],list[1]);
        f2(list);
    }
    
    int main()
    {
        auto a = std::initializer_list<double>{1.0,2.0,3.0};
        f(a);
    }
    

    DEMO

    Note that the previous code can be made more generic. But it should be ok to get the idea.