mardi 27 décembre 2016

DRY way to construct all elements of an array with the same initializer list?

In C++11, is there a DRY way to construct all elements of an array with some same set of parameters for all elements? (e.g. via a single initializer list?)

For example:

class C {
public:
   C() {}
   C(int x) : m_x(x) {}
   int m_x;
};

// This would construct just the first object with a parameter of 1.
// For the second and third object the default ctor will be called.
C ar[3] {1};

// This would work but isn't DRY (in case I know I want all the elements in the array to be initialized with the same value.
C ar2[3] {1, 1, 1};

// This is DRYer but obviously still has redundant repetition.
const int initVal = 1;
C ar3[3] {initVal, initVal, initVal};

I know my goal is easily achievable by using an std::vector. I'm wondering if it's possible with raw arrays as well.

Aucun commentaire:

Enregistrer un commentaire