Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

initializing a const array in the constructor

Tags:

c++

arrays

c++11

I am trying to achieve something like this

struct A {
    A(const int (&arr)[5])
      :  arr_(arr)
    {}

    const int arr_[5];
}

and obviously this doesn't work. My intent is to keep arr_ field constant. What is the best way to achieve this (can be C++11)?

like image 274
hovnatan Avatar asked Jan 05 '23 20:01

hovnatan


2 Answers

Use std::array:

struct A {
    A(std::array<int, 5> const& arr)
      :  arr_(arr)
    {}

    std::array<int, 5> const arr_;
}
like image 94
ecatmur Avatar answered Jan 15 '23 21:01

ecatmur


With forwarding constructor:

struct A {
    A(const int (&arr)[5]) : A(arr, std::make_index_sequence<5>()) {}

    const int arr_[5];
private:
    template <std::size_t ... Is>
    A(const int (&arr)[5], std::index_sequence<Is...>)
      : arr_{arr[Is]...}
    {}
};
like image 41
Jarod42 Avatar answered Jan 15 '23 21:01

Jarod42