11

I would like to create a constructor, which is similar to the int array constructor: int foo[3] = { 4, 5, 6 };

But I would like to use it like this:

MyClass<3> foo = { 4, 5, 6 };

There is a private n size array in my class:

template<const int n=2>
class MyClass {

    public:

        // code...

    private:

        int numbers[n];

        // code...

};
Iter Ator
  • 8,226
  • 20
  • 73
  • 164

1 Answers1

18

You need a constructor that accepts a std::initializer_list argument:

MyClass(std::initializer_list<int> l)
{
    ...if l.size() != n throw / exit / assert etc....
    std::copy(l.begin(), l.end(), &numbers[0]);
}

TemplateRex commented...

You might want to warn that such constructors are very greedy and can easily lead to unwanted behavior. E.g. MyClass should not have constructors taking a pair of ints.

...and was nervous a hyperactive moderator might delete it, so here it is in relative safety. :-)

Community
  • 1
  • 1
Tony Delroy
  • 102,968
  • 15
  • 177
  • 252
  • 5
    You might want to warn that [such constructors are very greedy](http://stackoverflow.com/q/19847960/819272) and can easily lead to unwanted behavior. E.g. `MyClass` should not have constructors taking a pair of `int`s e.g. – TemplateRex Jan 15 '16 at 12:48
  • [see here](http://stackoverflow.com/questions/34717823/can-using-a-lambda-in-header-files-violate-the-odr#comment57382669_34721371) for greedy moderation. – TemplateRex Jan 15 '16 at 21:33