This:
constexpr const std::array<int, 3> {{
0,
1
}};
compiles OK.
But how to check (in compile-time) that whole array is filled? May be some static_assert
?
This:
constexpr const std::array<int, 3> {{
0,
1
}};
compiles OK.
But how to check (in compile-time) that whole array is filled? May be some static_assert
?
You could write a wrapper to generate the array for you and carry out the check:
template <typename T, std::size_t N, typename... Ts>
std::array<T, N> make_array (Ts&&... ts) {
static_assert(N == sizeof...(Ts), "Must supply N arguments");
return {{ std::forward<Ts>(ts)... }};
}
But with that function you may as well just deduce the size of the array from the arguments:
template <typename T, typename... Ts>
std::array<T, sizeof...(Ts)> make_array (Ts&&... ts) {
return {{ std::forward<Ts>(ts)... }};
}
As an enhancement to TartanLlama answer i would wrap the initializing routine into another macro to provide the possibility to create proper documentation and better readability (Since the op mentioned that this is a safety check for other programmers).
template <typename T, T ...ts>
struct ArrayInitializer {
const std::array<T, sizeof...(ts)> ARRAY = {{ ts... }};
};
/*
* @document me
*/
#define MAKE_ARRAY(name, ...) \
constexpr const auto name = ArrayInitializer<int, ##__VA_ARGS__ >().ARRAY;
// Create array with x elements
MAKE_ARRAY(arrayName, 1, 2, 3, 4);