lundi 7 décembre 2015

Brackets operator overload on std::array

So, consider the following code:

#include <iostream>
#include <array>

template<class T, std::size_t N, std::size_t N2>
struct foo
{
    std::array<std::array<T, N2>, N> data;

    T& operator[](std::size_t index) { return data[index]; }
};

int main()
{
    foo<int, 3, 3> obj;
    std::cout << obj[2][2]; //boom
}

This is my logic: obj[2] by itself returns a std::array<T, N2> object, so applying operator[] again to that (obj[2][2]), should give me the result I need. So actually with obj[2] it's calling foo's operator[], while with obj[2][2] it's calling std::array<T, N>'s operator[]. Obviously not.

Question: What is going on in the example above and why is my logic faulty?

Aucun commentaire:

Enregistrer un commentaire