Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I want to initialize an array with a sequence of ints from 0 to N - 1

#include <array>
#include <iostream>

template<unsigned N>
struct XArray
{
    static constexpr int array[N] = {XArray<N - 1>::array, N - 1};
};

template<>
struct XArray<1>
{
    static constexpr int array[1] = {0};
};


int main(void)
{
    std::array<int, 10> const   a{XArray<10>::array};

    for (int const & i : a)
        std::cout << i << "
";
    return 0;
}

I tried that, but it does not work, since XArray<N - 1>::array in my struct must be int, and not int *. How can I do this ? How to "concatenate" the values ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
396 views
Welcome To Ask or Share your Answers For Others

1 Answer

I'm not sure if this meets your requirements.

#include <array>
#include <iostream>

template <size_t ...I>
constexpr auto init(std::index_sequence<I...>) {
    return std::array<size_t, sizeof...(I)>{I...};
}

int main(void)
{
    std::array<size_t, 10> a = init(std::make_index_sequence<10>());

    for (int const & i : a)
        std::cout << i << "
";
    return 0;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...