jeudi 23 janvier 2020

How to dispatch between assert() and static_assert(), dependend if in constexpr context?

In C++11 constexpr functions, a second statement such as an assert() is not possible. A static_assert() is fine, but wouldn't work if the function is called as 'normal' function. The comma operator could come to help wrto. the assert(), but is ugly and some tools spit warnings about it.

Consider such 'getter' which is perfectly constexpr-able beside the assertion. But I would like to keep some kind of assertion for runtime and compile time, but cannot just overload depending on the 'constexpr' context.

template<int Size>
struct Array {
  int m_vals[Size];
  constexpr const int& getElement( int idx ) const
  {
    assert( idx < Size ); // a no-go for constexpr funcs in c++11
    static_assert( idx < Size, "out-of-bounds" ); // a no-go for non-constexpr calls
    return m_vals[idx];
  }
};

Side conditions: C++11, no heap, no exceptions, no compiler specifics.

Aucun commentaire:

Enregistrer un commentaire