Skip to content

Instantly share code, notes, and snippets.

@htfy96
Created July 15, 2017 11:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save htfy96/0691e2801d8e7d9f59ad663974a109b9 to your computer and use it in GitHub Desktop.
Save htfy96/0691e2801d8e7d9f59ad663974a109b9 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <array>
#include <cassert>
using namespace std;
constexpr int f()
{
return 42;
}
int g()
{
static int cnt;
return ++cnt;
}
template<typename T, std::size_t ... Is>
constexpr array<int, sizeof...(Is)> helper(T f, index_sequence<Is...>)
{
return array<int, sizeof...(Is)> { ((void)Is, f())... };
}
template<int N, typename T>
constexpr auto create_int_arr_with_length_n(T f) -> array<int, N>
{
return helper(f, make_index_sequence<N>());
}
int main()
{
constexpr auto arr = create_int_arr_with_length_n<10>(f);
static_assert(arr.size() == 10, "");
static_assert(arr[9] == 42, "");
auto a2 = create_int_arr_with_length_n<10>(g);
assert(a2.size() == 10);
assert(a2[5] == 6);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment