0

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?

Learning Lin
  • 121
  • 1
  • 7

1 Answers1

1

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.

davidhigh
  • 14,652
  • 2
  • 44
  • 75
  • `std::distance(std::begin(list),std::end(list))` can be simplified using `list.size()` instead. But you don't need that, since `std::span{std::next(std::begin(list)), size}` can be simplified using `std::span{list.begin()+1, list.end()}` instead (just be sure `list` is not empty first). Also, `auto a = std::initializer_list{1.0,2.0,3.0}; f(a);` can be simplified to `f({1.0,2.0,3.0});` [Demo](https://coliru.stacked-crooked.com/a/a550c936536a50ac) – Remy Lebeau May 06 '22 at 08:50
  • Of course, you don't actually need the `std::span` to call `f1()` in this example, eg: `void f(std::initializer_list list){ if (list.size() > 2) { f1(*(list.begin()+1), *(list.begin()+2)); } }` – Remy Lebeau May 06 '22 at 08:57
  • @Remy Lebeau: First point: sure, but I like the free functions, moreover I prefer prev/next to pointer arithmetic (e.g. because of [this](https://stackoverflow.com/questions/5322104/how-portable-is-end-iterator-decrement)). Second point: yes, if it's only about calling a fixed signature, that's better, thanks for pointing. – davidhigh May 06 '22 at 10:42