Mayhem
Mayhem

Reputation: 507

std::array class member set during compile time?

I have a class with private member std::array<int,10> m_arr; which contains zeros by default, but in one case it must be set to something else. There is a setter for that class

void setArray(const std::array<int,10>& arr)
{
    m_arr=arr;
}

However I was wondering if the setting can be done compile time somehow for that specific case? Thanks in advance.

Upvotes: 1

Views: 278

Answers (1)

skypjack
skypjack

Reputation: 50550

A possible solution can be the following one:

#include<utility>
#include<array>

struct S {
    constexpr S(): arr{} { }

    template<std::size_t... I>
    constexpr S(std::integer_sequence<std::size_t, I...>): arr{ I... } { }

    std::array<std::size_t, 10> arr;
};

int main() {
    constexpr S s1{};
    constexpr S s2{std::integer_sequence<std::size_t, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1>{}};
    // equivalent to: constexpr S s3{std::integer_sequence<std::size_t, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9>{}};
    constexpr S s3{std::make_index_sequence<10>{}};
}

Note that integer_sequence is part of the C++14 revision.
Anyway, you can find online an implementation of such a structure that is suitable for C++11 based projects.

Upvotes: 1

Related Questions