使用模板初始化序列数组

Sequence array initialization with template

本文关键字:数组 初始化      更新时间:2023-10-16

我想用从0N - 1int序列初始化数组

#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 << "n";
    return 0;
}

我尝试过,但它不起作用,因为我的结构中的XArray<N - 1>::array必须是int,而不是int *。我该怎么做?如何"连接"这些值?

我不确定这是否符合您的要求。

#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 << "n";
    return 0;
}

您可以创建一个make_array函数模板,该模板将返回所需的std::array,其中包含从0N-1的元素,如下所示:

C++17版本

template<std::size_t N> std::array<int, N> constexpr make_array()
{
    std::array<int, N> tempArray{};
    int count = 0;
    for(int &elem:tempArray)
    {
        elem = count++;
    }
    return tempArray;
}
int main()
{
    
    //-------------------------------vv------>pass the size here 
    constexpr auto arr  = make_array<10>();
   
    
    //lets confirm if all objects have the expected value 
    for(const auto &elem: arr)
    {
        std::cout << elem << std::endl; //prints 1 2 3 4 5 6 7 8 with newline in between
    }
    
}

工作演示C++17

上述程序的输出为:

0
1
2
3
4
5
6
7
8
9

C++11版本

由于std::array::begin不是C++11中的constexpr,因此constexpr已被移除。

template<std::size_t N> std::array<int, N> make_array()
{
    std::array<int, N> tempArray{};
    int count = 0;
    for(int &elem:tempArray)
    {
        elem = count++;
    }
    return tempArray;
}
int main()
{
    
    //---------------------vv------>pass the size here 
    auto arr  = make_array<10>();
   
    
    //lets confirm if all objects have the expected value 
    for(const auto &elem: arr)
    {
        std::cout << elem << std::endl; //prints 1 2 3 4 5 6 7 8 with newline in between
    }
    
}

工作演示C++11