C++17 construct array in stack using chosen constructor (same constructor parameter values for each array entry)

痞子三分冷 提交于 2019-12-11 14:31:31

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/41428365/c17-construct-array-in-stack-using-chosen-constructor-same-constructor-parame

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!