数组初始化编译时间-Constexpr序列 [英] Array Initialisation Compile Time - Constexpr Sequence

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

问题描述

我正在阅读关于此问题的问题.

这个问题本身并不那么有趣,但是我想知道它是否存在以及如何实现编译时解决方案.

The question itself is not so interesting, but I was wondering whether it exists and how to implement a compile time solution.

关于第一个序列:

除可以除以3的数字以外的所有数字.

All numbers except the ones which can be divided by 3.

序列应类似于:

[1, 2, 4, 5, 7, 8, 10, 11, 13, 14, ...]

通过归纳,我找到了该序列的数学公式:

By induction, I've found the math formula for that sequence:

 f(0) = 0;
 f(x > 0) = floor[(3x - 1) / 2];

因此,我实现了C ++ constexpr函数,该函数按以下顺序生成 i 个数字:

So I've implemented a C++ constexpr function which generates the i-th number in the sequence:

#include <type_traits>

template <typename T = std::size_t>
constexpr T generate_ith_number(const std::size_t index) {
  static_assert(std::is_integral<T>::value, "T must to be an integral type");

  if (index == 0) return 0;
  return (3 * index - 1) / 2;
}

现在,我想生成一个编译时数组/序列" ,它存储序列的前N个数字.

Now I'd like to generate a "compile-time array/sequence" which stores the first N-th numbers of the sequence.

结构应类似于:

template <typename T, T... values>
struct sequence {};

template <typename T, std::size_t SIZE>
struct generate_sequence {};  // TODO: implement

问题(不止一个,但彼此相关):

Questions (more than one, but related among them):

1)如何实现这种integer_sequence?

2)是否可以在编译时从该integer_sequence构建一个std::array?

2) Is it possible to build an std::array from that integer_sequence at compile time?

推荐答案

1)如何实现这种integer_sequence?

template <std::size_t... Is> 
constexpr auto make_sequence_impl(std::index_sequence<Is...>)
{
    return std::index_sequence<generate_ith_number(Is)...>{};
}

template <std::size_t N> 
constexpr auto make_sequence()
{
    return make_sequence_impl(std::make_index_sequence<N>{});
}


2)是否可以在编译时从该integer_sequence构建一个std::array?

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

template <typename Seq>
constexpr auto make_array_from_sequence(Seq)
{
    return make_array_from_sequence_impl(Seq{});
}


用法:


Usage:

int main()
{
    constexpr auto arr = make_array_from_sequence(make_sequence<6>());
    static_assert(arr[0] == 0);
    static_assert(arr[1] == 1);
    static_assert(arr[2] == 2);
    static_assert(arr[3] == 4);
    static_assert(arr[4] == 5);
    static_assert(arr[5] == 7);
}

在wandbox.org上的实时示例

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

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