0

Is it a way in c++17 to construct an array in stack using another constructor than the default constructor.

This is a special case when each array value is constructed with the same constructor parameters.

I need to use a basic stack located array (not a vector or an array of pointers or something else).

This code illustrate what I would like to do :

#include <iostream>
using namespace std;

struct A {
    A() {
        printf("A() called\n");
    }

    A(int i, int j) {
        printf("A(%d, %d) called\n", i, j);
    }
};

struct B {
    A tab[100];

    B(int i, int j) {
        // I would like to call A(i, j) for each tab entries instead of the default constructor
        printf("B(%d, %d) called\n", i, j);
    }
};

int main() {
    B b(1, 7);
    return 0;
}

Thanks

Stephen Docy
  • 4,738
  • 7
  • 18
  • 31
infiniteLoop
  • 383
  • 2
  • 12

1 Answers1

2

The usual delegating constructor + integer sequence + pack expansion trick:

struct B {
    A tab[100];

    template<size_t... Is>
    B(int i, int j, std::index_sequence<Is...>) : tab{ {(void(Is), i), j }... } {}

    B(int i, int j) : B(i, j, std::make_index_sequence<100>()) {}
};

Search SO for implementations of make_index_sequence and friends in C++11.

T.C.
  • 133,968
  • 17
  • 288
  • 421