在构造函数中初始化私有std :: array成员 [英] Initializing private std::array member in the constructor

查看:164
本文介绍了在构造函数中初始化私有std :: array成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I was wondering what is the proper way to initialize a std::array member of the class in the constructor, when the initial array values are parameters to the constructor?

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

More specifically, consider the following example:

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

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

Obviously one way is to write list({Car(color,age), Car(color,age), Car(color,age)}), but this clearly does not scale if we wanted 30 identical cars instead of three.

如果我使用的是std::vector而不是std::vector,那么解决方案应该是list(3, Car(color,age)(或list(30, Car(color, age))),但是由于我的问题是知道列表的大小,所以我认为使用.

If instead of std::array I used std::vector the solution would have been list(3, Car(color,age) (or list(30, Car(color, age)) but as in my problem the size of the list is known, I thought it is more correct to use std:array.

推荐答案

数组版本的一个选项是使用模板函数来构建数组.您必须测试一下,看看它是否已优化或在发布模式下复制了,

One option for the array version is to use a template function to build the array. You'll have to test to see if this gets optimized out or copied in release mode,

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

演示

这篇关于在构造函数中初始化私有std :: array成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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