I have a class B
that is supposed to contain a private std::array<A*>
, and the size will be sent in through the constructor.
class B
{
public:
B(size_t s) : vv(s,nullptr), aa(s) {}
// ... more stuff
private:
std::vector<A*> vv; // vector works fine
std::array<A*,??> aa; // but how to initialize an array??
}
This works fine with using std::vector
, but it seems I cannot get it to work with std::array
.
Adding another member const size_t ss
and using it in the std::array
declaration doesn't work either, even if it is a static const size_t ss
- the compiler (VS2019 16.1.5, set to C++17) claims "...expected compile-time constant..."
class B // another try with a static const size_t
{
public:
B(size_t s) : ss(s), aa(s) {}
// ... more stuff
private:
static const size_t ss;
std::array<A*,ss> aa; // no, ...expected compile-time constant...
}
That message seems to imply there is no way - if the size needs to be known at compile time, it needs to be the same for all instances/objects of the class - which directly contradicts my plan.
Of course, I could make a template class, or I could simply stay with std::vector
; or I could use a kind of 'PIMPL' (declare instead a pointer to that array, and create it with new
in the constructor) - that's not the question.
The question is: Can I pass the size of the to-be array in the constructor, and directly create it from that?
Is there any fancy construct or trick?
[Note: not a duplicate of Initializing private std::array member in the constructor, or Initializing std::array private member through constructor, or How to construct std::array object with initializer list? - I don't want to pass values, but the size of the array]