If your argument is known at compile time, you can use static_assert .
#include <cassert>; constexpr float Vec4::operator[](const unsigned int i) { static_assert(i <= 3); ... }
Static statements do not affect performance because they are checked at compile time.
If your argument is not known at compile time, you can use dynamic assert .
#include <cassert>; float Vec4::operator[](const unsigned int i) { assert(i <= 3); ... }
Dynamic statements are contained in the compiler output only after setting the compiler flags that enable them, so they can be easily disabled.
Or you can just throw an exception .
float Vec4::operator[](const unsigned int i) { if (i > 3) { throw BadArgumentException("i must be <= 3"); } ... }
Exceptions can contain a lot of information and be processed in other parts of the code, but have the greatest performance.
http://en.cppreference.com/w/cpp/error/assert
source share