0

C++. Imagine I'm putting together a class for statically sized, bounds checked array:

template<typename T, int N>
class MyArray
{
    T a[N];
public:
    T & operator[](int i)
    {
         if(i < 0 || i >= N)
             OnError(); //Crash and die horribly
         return a[i];
    }
};

Is there a way to avoid performing a bound check at run time if the array access operator is invoked with a compile time constant as an argument?

4
  • 3
    Add a constexpr overload? If, C++20, consteval Commented Mar 4, 2021 at 2:23
  • 1
    Turn the function argument into a template parameter? Commented Mar 4, 2021 at 2:24
  • 3
    "I'm putting together a class for statically sized, bounds checked array" - so, you are intentionally reproducing what std::array and its at() method already do? Commented Mar 4, 2021 at 2:32
  • @Remy: long story there. std::array as it is won't do. The question says "imagine". Commented Mar 4, 2021 at 14:39

1 Answer 1

1

Is there a way to avoid performing a bound check at run time if the array access operator is invoked with a compile time constant as an argument?

You don't necessarily need to do anything yourself other than enable the optimiser. Compilers are smart, can expand function calls inline and can fold branches that are known at compile time.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.