Search code examples
c++constructorinitializationinitializer-listcurly-braces

Using brace-init for a non-trivial multi-variable class


I am trying to make a certain template class brace-initializable, e.g.

template<typename T>
class A {
    private:
        std::vector<T> _data;
        std::size_t _m;
        std::size_t _n;

    public:
        Matrix(std::size_t m, std::size_t n, const T &fill); // regular (non-trivial) constructor
        Matrix(std::initializer_list<T> list);
};

However, I'm having trouble coming up with the implementation. I want to be able to do:

A<int> a = {{1, 2, 3, 4}, 2, 2};
// or something similar...e.g. C++11 style brace-init
A<int> a {{1, 2, 3, 4}, 2, 2};

I've tried:

template<typename T>
Matrix<T>::Matrix(std::initializer_list<T> list)
    : _data(*list.begin()),
      _m(*(list.begin() + 1)),
      _n(*(list.begin() + 2)) {}

But that doesn't work for me. Help!


Solution

  • In order to convert from an initializer_list to a vector you may copy all the elements. STL makes this pretty nice with the begin/end iterators. Here's all the possible constructors for vector

        Matrix(std::initializer_list<T> list, std::size_t m, std::size_t n)
        : _data(list.begin(), list.end()) // This is what might help
        , _m(m)
        ,_n(n)
        {
    
        }