Compile time range check in std::array

Viewed 189

I would like to perform range check for a std::array at compile time. Here is an example:

#include <iostream>
#include <array>

void rarelyUsedFunction(const std::array<double, 2>& input)
{
    std::cout << input[5] << std::endl;
}

int main()
{
    std::array<double, 2> testArray;
    rarelyUsedFunction(testArray);
}

If I compile this with g++ there is no warning or error, despite the undefined access to an element which is not in the array. The compiled program just prints some random value.

Is there a compiler option in g++ for a suitable range/boundary check, that is performed during compile time? I know that I can add "-D_GLIBCXX_DEBUG" but this will only perform a check during runtime. If I have a function which is not called very often, this won't be triggered.

I am aware, that such a range check could not be performed in all circumstances, but in the case above, the compiler should be able to spot the problem!?

1 Answers

As mentioned in the comments, std::get(std::array) will do that nicely for you, since it is obligated to do such bounds checking:

I must be an integer value in range [0, N). This is enforced at compile time as opposed to at() or operator[].

In your example, it would look like this:

void rarelyUsedFunction(const std::array<double, 2>& input)
{
    std::cout << std::get<5>(input) << std::endl; // <---- Compilation error!
}

If the index is not just a literal, you can still calculate it with "complex" code as long as you manage to stuff it in a constexpr variable:

void rarelyUsedFunction(const std::array<double, 2>& input)
{
    constexpr std::size_t index = /* Whatever, as long as it compiles... */;
   
    std::cout << std::get<index>(input) << std::endl;
}

Obviously, in either case, this involves providing the compiler with a hard guarantee that the index is known at compile time.

Related