使用模板的序列数组初始化 [英] Sequence array initialization with template

查看:238
本文介绍了使用模板的序列数组初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要从 0 初始化一个 int N-1

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

我试过了,但它不工作,因为 XArray< N-1> :: array 在我的结构中必须是 int ,而不是 int * 。我如何做到这一点?如何连接值?

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 ?

推荐答案

我不知道这是否符合您的要求。

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

这篇关于使用模板的序列数组初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆