Created
July 15, 2017 11:45
-
-
Save htfy96/0691e2801d8e7d9f59ad663974a109b9 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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