jkang
jkang

Reputation: 549

c++ initialize std::array of std::arrays in the initializer list using constructor parameters

I have a constructor as such:

class MyClass {
  protected:
    std::size_t size1;
    std::size_t size2;
    std::array<std::array<std::pair<std::uint64_t, std::uint64_t>>> items;
  public:
    MyClass(): MyClass(1, 1, <???>) {}
    MyClass(std::size_t size1, std::size_t size2): size1(size1), size2(size2), <???> {}
};

I'm not sure if the above part can be done: to initialize the array of arrays of pairs to all 0 based on the sizes provided by size1 and size2. I've Googled around a bit but can't seem to run into code examples of this. Any help would be appreciated.

Upvotes: 0

Views: 193

Answers (1)

G. Sliepen
G. Sliepen

Reputation: 7973

As Yksisarvinen mentioned, std::array needs to know its size at compile time. If you need to set the size at runtime, then use std::vector instead. However, if you do know the size at compile time, then make MyClass a template and pass the desired sizes as template parameters:

template<std::size_t size1 = 1, std::size_t size2 = 1> {
protected:
    std::array<std::array<..., size2>, size1> items{};
public:
    MyClass() = default;
    ...
};

Note that the {} after the declaration of items ensures all the values are set to zero. And then you can instantiate it like so:

MyClass<3, 5> myObject;

Upvotes: 3

Related Questions