Why can we not access elements of a tuple by index?

Because [] is an operator (named operator[]), thus a member function, and is called at run-time.

Whereas getting the tuple item is a template mechanism, it must be resolved at compile time. Which means this can be only done with the <> templating syntax.

To better understand, a tuple may store different types. A template function may return different types depending on the index passed, as this is resolved at compile time.
The operator[] must return a unique type, whatever the value of the passed parameter is. Thus the tuple functionality is not achievable.

get<0>(x) and get<1>(x) are two different functions generated at compile time, and return different types. The compiler generates in fact two functions which will be mangled to something like

int get_tuple_int_string_int_0(x)

and

string get_tuple_int_string_int_1(x)

Leave a Comment