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
// not possible, even in constexpr calls as being pointed out, but what I would like:
static_assert( idx < Size, "out-of-bounds" );
return m_vals[idx];
}
};
Side conditions: C++11, no heap, no exceptions, no compiler specifics.
Note as commenters pointed out (thanks!), static_assert on the argument is not possible (but would be nice). The compiler gave me a different error on out-of-bounds access in that situation.
static_assertdependent onidxat all. You can only diagnose a wrong value ofidxif the function is used in a context that requires a constant expression, by forcing the evaluation of a construct that makes it not a constant expression. Outside of such context, you can never check the value at compile-time.