Ivaylo Valchev
Ivaylo Valchev

Reputation: 10425

Brackets operator overload on std::array<std::array<T, N2>, N> data member

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?

Upvotes: 0

Views: 63

Answers (2)

Guillaume Racicot
Guillaume Racicot

Reputation: 41820

The return type of the operator[] is not right. The expression data[index] is of the type std::array<T, N2> and You tell the compiler you return a T&, which is false. Your function should look like this:

std::array<T, N2>& operator[](std::size_t index) { return data[index]; }

Upvotes: 2

hlt
hlt

Reputation: 6317

Look at your operator[]. It returns T&, which in your case is int&. data[index], on the other hand, is of type std::array<T, N2>&, which in this case is std::array<int, 3>&.

Changing the operator's return type should fix this:

    std::array<T, N2>& operator[](std::size_t index) { return data[index]; }

Upvotes: 1

Related Questions