在构造函数中初始化private std :: array成员

kMa*_*ter 4 c++ initializer-list stdarray

std::array当初始数组值是构造函数的参数时,我想知道在构造函数中初始化类成员的正确方法是什么?

更具体地说,请考虑以下示例:

class Car {
  public:
    Car(const std::string& color, int age): color_(color), age_(age) {}
    // ...
  private:
    std::string color_;
    int age_;
};

class ThreeIdenticalCars {
  private:
    std::array<Car, 3> list;
  public:
    ThreeIdenticalCars(const std::string& color, int age):
    // What to put here to initialize list to 3 identical Car(color,age) objects?
   {}
};
Run Code Online (Sandbox Code Playgroud)

显然,一种方法是写作list({Car(color,age), Car(color,age), Car(color,age)}),但如果我们想要30辆相同的汽车而不是3辆,这显然无法扩展.

如果不是std::array我使用std::vector的解决方案list(3, Car(color,age)(或者list(30, Car(color, age))在我的问题中,列表的大小已知,我认为使用更正确)std:array.

rma*_*son 6

阵列版本的一个选项是使用模板函数来构建阵列.你必须进行测试,看看它是否在发布模式下被优化或复制,

   #include <iostream>
#include <array>
#include <tuple>

class Car {
    public:
    Car(const std::string& color, int age): color_(color), age_(age) {}
    // ...
    //private:
    std::string color_;
    int age_;
};

template <typename CarType, typename... Args ,size_t... Is>
std::array<CarType,sizeof...(Is)> make_cars(std::index_sequence<Is...>,Args&&... args )
{
    return { (Is,CarType(args...))... };
}

class ThreeIdenticalCars {
    //private:
    public:
    std::array<Car, 3> list;
  //public:
    ThreeIdenticalCars(const std::string& color, int age) : 
        list(make_cars<decltype(list)::value_type>(
            std::make_index_sequence<std::tuple_size<decltype(list)>::value>(),
            color,
            age
            ))
   {}
};

int main()
{
    ThreeIdenticalCars threecars("red", 10);

    for(auto& car : threecars.list)
        std::cout << car.color_ << " " << car.age_ << std::endl;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

演示