Take a variable number of arguments and put them in std :: vector

I make a class - let it be Container- it just contains std::vectorsome special logic that decides how vector values ​​are chosen. I want to add a method to add multiple values ​​to my class with one call. This is my method that adds one element:

void LoopGenerator::add(RandomStripe &stripe)
{
    stripes.push_back(new SingleStripe(stripe));
}

I need a similar method that will be called like this:

LoopGenerator gen = LoopGenerator();
gen.add(RandomStripe(), RandomStripe(), RandomStripe() ... and as much as you want ... );

and add all the parameters to the internal one std::vector.

Can this be done only with standard libraries, or is it best without them?

+4
source share
2 answers

You can use std :: initializer_list. for instance

#include <initializer_list>
#include <algorithm>
#include <vector>
#include <iterator>    


//...

void LoopGenerator::add( std::initializer_list<RandomStripe> stripe )
{
    std::transform( stripe.begin(), stripe.end(), 
                   std::back_inserter( stripes ),
                   []( const RandomStripe &s ) { return new SingleStripe( s ); } );
}

And name it like

gen.add( { RandomStripe(), RandomStripe(), RandomStripe(), /*...*/ } );
+5

++ 11, .

:

LoopGenerator& LoopGenerator::add(RandomStripe &stripe)
{
    stripes.push_back(new SingleStripe(stripe));
    return *this;
}

gen.add(RandomStripe()).add(RandomStripe()).add(RandomStripe());

0

All Articles