user3325997
user3325997

Reputation: 33

How to create a constructor initialized with a list?

How can I initialize a constructor using a list with n elements?

X x = {4, 5, 6, ...};

Upvotes: 3

Views: 627

Answers (3)

Alex
Alex

Reputation: 3381

For a list with n elements you need to use std::initializer_list.

Initializer_list objects are automatically constructed as if an array of elements of type T was allocated, with each of the elements in the list being copy-initialized to its corresponding element in the array, using any necessary non-narrowing implicit conversions.

Follows a example:

#include <iostream>
#include <initializer_list>
#include <vector>

template<class T>
class X {
  long unsigned int size;
  std::vector<T> _elem;
public:
  X(std::initializer_list<T> l): size{l.size()} {
    for(auto x: l)
      _elem.push_back(x);
  }

  void print() {
    for(auto x: _elem)
      std::cout << x << " ";
  }
};

int main(int argc, char **argv) {
  X<int> x = {4, 5, 10 ,8 ,6};
  x.print();
  return 0;
}

For more information about std::initializer_list: http://www.cplusplus.com/reference/initializer_list/initializer_list/

Upvotes: 7

Vlad from Moscow
Vlad from Moscow

Reputation: 310980

You can define a so-called initializer-list constructor and use iterators of class std::initializer_list to access elements in the list.

According to the C++ Standard

an initializer-list constructor if its first parameter is of type std::initializer_list or reference to possibly cv-qualified std::initializer_list for some type E, and either there are no other parameters or else all other parameters have default arguments

For example

#include <iostream>
#include <vector>
#include <initializer_list>

class A
{
public:
   A() = default;
   A( std::initializer_list<int> l ) : v( l ) {}
   std::vector<int> v;
};

int main() 
{
    A a = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

    for ( int x : a.v ) std::cout << x << ' ';
    std::cout << std::endl;

    return 0;
}

Upvotes: 2

Casey
Casey

Reputation: 42554

Are you asking how to make a constructor that accepts an initializer_list?

#include <initializer_list>

class X {
public:
  X(std::initializer_list<int> ilist);
};

Upvotes: 2

Related Questions