(Note that as far as I see, std::array
with std::get
already solves your problem.)
The main issue is that you need your instance aw
to be constexpr
and of course you need to initialize it with some values:
constexpr array_wrapper<3> aw = { 1, 2, 3 };
Regarding the function at
, you can write it as a normal function but simply specify it as constexpr
:
constexpr int const& at(int i) const {
return arr[i];
}
Then, aw.at(0)
can be used as a constant expression: Live Demo
The advantage of this is that you can use this function in both compile-time and runtime expressions, with static and dynamic indexing, respectively.
If you really want it to be templated, you can either write it as a non-member like std::get<N>
or as a class member, but use a template parameter of type int
(or size_t
or similar). That simplifies its definition (and you can get rid of your compile_time_int
class template):
template<int Index>
constexpr int const& at() const {
return arr[Index];
}
Then, aw.at<0>()
can be used as a constant expression: Live Demo
The advantage of the second method is that the index is guaranteed to be static, so we can use it in the function for static bound checking, which will not add any performance penalty. I don't know if this is possible with the first version.