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...

};
2
  • 5
    Try googling c++11 initializer list Commented Jan 15, 2016 at 12:15
  • The type int[3] is not a class type, so it doesn't have a constructor. It can be initialized, but not via a constructor call. Commented Jan 15, 2016 at 12:36

1 Answer 1

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. :-)

Sign up to request clarification or add additional context in comments.

2 Comments

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 e.g.
see here for greedy moderation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.