vendredi 5 janvier 2018

Why is `std::array::at()` not implemented as a template function?

Edit: I forgot to mention that this would be in a constexpr context where there aren't any dynamical indices.

Consider the following (very naive) implementation:

template <class T, std::size_t N>
class array
{
    // ...

    template <size_type pos>
    reference at()
    {
        static_assert(pos < N, "Index out of range.");
        return m_data[pos];
    }
}

With the following usage:

int main()
{
    array<int, 5> a{1, 2, 3, 4, 5};

    cout << a.at(10) << "\n";   // will throw at runtime

    cout << a.at<10>() << "\n"; // static assert error; index out of range
    return 0;
}

This effectively prevents out of range access for the types and any nasty segfaults or exceptions that would be thrown. An error would be thrown by the compiler that looks like this:

error: static assertion failed: Index out of range
             static_assert(pos < N, "Index out of range");

And most IDEs would catch the erroneous access. So why is it not implemented as such?

Note: I'm sorry if this is obvious but I'm planning on writing my own array class for performance and safety, and this thought popped into my head.

Aucun commentaire:

Enregistrer un commentaire