【问题标题】:C++17 construct array in stack using chosen constructor (same constructor parameter values for each array entry)C++17 使用选择的构造函数在堆栈中构造数组(每个数组条目的构造函数参数值相同)
【发布时间】:2017-01-02 14:07:30
【问题描述】:

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

这是一种特殊情况,当每个数组值都使用相同的构造函数参数构造时。

我需要使用位于堆栈的基本数组(不是向量或指针数组或其他东西)。

这段代码说明了我想要做什么:

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

谢谢

【问题讨论】:

    标签: c++ c++11 c++14 c++17


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2013-04-29
      • 2017-02-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多