dog
dog

Reputation: 59

compile-time safe array in C++?

There's this homework question i've been wrecking my brain about:

I have to create an array class in C++ in which an index access to an element in the array is checked in compile-time, i.e. if I try to access the array with an index outside ita size it will cause a compilation error.

I thought I'd use enums as indexes instead of ints, but I spoke with my instructor and he told me that it's not the correct way, he also said that "think that for the same price you could use this to have an array where the indexes don't start at 0" or something like that.

I'd appreciate any suggestions!

Upvotes: 2

Views: 1753

Answers (4)

urzeit
urzeit

Reputation: 2909

You might have a chance to use a custom class as the index type. You can then limit the generation of an index element by limiting the operators of the class. Especially this can ensure that no user input can be used as an index (if you don't provide any method to convert an integer (or similar) to the index type. If you allow this, you have no chance at all!).

Upvotes: 0

sasha.sochka
sasha.sochka

Reputation: 14715

std::array from C++11 is just what you ask. It's an array with compile-time known size, which allows compile time checking out-of-bounds errors

Example:

std::array<int, 5> arr = {1, 2, 3, 4, 5};
std::get<3>(arr); // returns 4;
std::get<9>(arr); // COMPILE ERROR

Internally this array is implemented using templated array size (as you see from example, the second template argument in first line) and static_assert which performs compile-time checking for your condition (in this case it would be index < array_size). Also as you see in example you are using std::get instead of operator[], because, again, it uses templated argument as index, which has to be a constant expression (constexpr) to allow compile-time checking instead of run-time.

If you need a variable index, you can use old good operator[] but you won't have compile-time out-of-bounds checking which is clearly impossible to do at all.

Upvotes: 8

Bartek Banachewicz
Bartek Banachewicz

Reputation: 39390

A hint, maybe phrased a bit differently: if you want to check the index at compile time, its value must also be known at compile time. Now, how to pass something to, say, a function at compile time?

To signal an error at compile time, static_assert can be used rather easily.

Upvotes: 1

Konrad Rudolph
Konrad Rudolph

Reputation: 545975

Here is a hint: If you want to check values at compile time, you essentially only have one option: you need to use non-type template arguments.

The standard library type std::tuple implements his, so check it out for inspiration on how to solve this.

Upvotes: 5

Related Questions