I know the differences between T& operator[]();
and T operator[]()
, the former one returns a reference, the latter one returns a copy of the result.
But what confuses me is that the same expression container[idx]
could be used in the return statement for the two different kinds of return types in the declarations.
How is this goal (one returns a reference, the other returns a copy) is achieved by the compiler?
Here is the code snippet:
template<typename T>
class Array
{
public:
#ifdef RETURN_REFERENCE
T& operator[](int idx)
#else
T operator[](int idx)
#endif
{
assert(idx<size);
return container[idx]; // same expression works for T and T&
}
private:
enum {size =100};
T container[size];
}