gpt4 book ai didi

c++ - 使用模板进行序列数组初始化

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:33:28 24 4
gpt4 key购买 nike

我想用 int 序列初始化一个数组来自 0N - 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 << "\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;
}

关于c++ - 使用模板进行序列数组初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37297359/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com