There is a class and operator overloading []

template <class T, size_t N> class Vect { public: typedef unsigned int size_type; T coord[N] = {}; constexpr T& operator [] (size_type index) { return coord[index]; } } 

Is it possible to somehow check the value of the index argument in compile-time? (index> = 0 && index <N)

  • specifically for operator [], it is more logical to return a non-constant, in order to be able to change the value at a given index. The index is best checked at run time. Another thing, if another method checks - AR Hovsepyan

1 answer 1

To be able to check some value at compile time, this value must be used in the appropriate context. The function argument is not relevant to this context. But if you implement a template function with a non-type parameter, then this can already be done. True syntax will be different:

 #include <cstdlib> template <class T, size_t N> class Vect { public: typedef unsigned int size_type; T coord[N] = {}; template <size_type I> constexpr T& get() { static_assert(I < N); return coord[I]; } }; int main() { Vect<int, 10> v; v.get<9>(); // OK v.get<10>(); // Ошибка компиляции } 

Similar functionality already exists in the standard library when using std::get on std::array .