数组初始化编译时间 - Constexpr序列

时间:2017-08-29 13:20:40

标签: c++ arrays c++11 constexpr compile-time

我正在阅读Check this online问题。

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

关于第一个序列:

  

除了可以除以3之外的所有数字。

序列应该是这样的:

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

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

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

所以我实现了一个C ++ constexpr函数,它在序列中生成 i-th 数字:

#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个数字。

结构应该是这样的:

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

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

问题(不止一个,但在其中相关):

1)如何实现这种integer_sequence

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

2 个答案:

答案 0 :(得分:12)

  

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)是否可以在编译时从std::array构建integer_sequence

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{});
}

用法:

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);
}

live example on wandbox.org

答案 1 :(得分:0)

It is pretty straightforward to generate the array using fairly straightforward code in recent C++:

<head></head>
相关问题