I was trying to write an compile-time valarray that could be used like this:
constexpr array<double> a = { 1.0, 2.1, 3.2, 4.3, 5.4, 6.5 };
static_assert(a[0] == 1.0, "");
static_assert(a[3] == 4.3, "");
static_assert(a.size() == 6, "");
I managed to do it with the following implementation and it works fine (with GCC 4.7):
#include <initializer_list>
template<typename T>
struct array
{
private:
const std::size_t _size;
const T* _data;
public:
constexpr array(std::initializer_list<T> values):
_size(values.size()),
_data(values.begin())
{}
constexpr auto operator[](std::size_t n)
-> T
{
return _data[n]
}
constexpr auto size() const
-> std::size_t;
{
return _size;
}
};
Even though it works fine for me, I am not sure about the behaviour of std::initializer_list
and may use some that are undefined behaviour.
constexpr
for std::initializer_list
constructor, begin
and size
is fine even though it is not strictly speaking C++11 since N3471 recently got adopted and made it to the standard.
Concerning the undefined behaviour, I am not sure whether the underlying array of the std::initializer_list
will live or if not, whether there is a mean to have it live longer than only array's
constructor. What do you think?
EDIT: I may not have been clear, but I do not really care about the actual array. What really interests me is the behaviour of std::initializer_list
and its underlying array at compile-time.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…