C ++ 17使用选定的构造函数在堆栈中构造数组(每个数组条目的构造函数参数值相同) [英] C++17 construct array in stack using chosen constructor (same constructor parameter values for each array entry)

查看:71
本文介绍了C ++ 17使用选定的构造函数在堆栈中构造数组(每个数组条目的构造函数参数值相同)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是c ++ 17中使用默认构造函数以外的其他构造函数在堆栈中构造数组的一种方法。

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;
}

谢谢

推荐答案

通常的委托构造函数+整数序列+包扩展技巧:

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>()) {}
};

在SO中搜索 make_index_sequence 和朋友的实现在C ++ 11中。

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

这篇关于C ++ 17使用选定的构造函数在堆栈中构造数组(每个数组条目的构造函数参数值相同)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆