Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

stl

tuple <int, string, int> x=make_tuple(1, "anukul", 100); cout << x[0];       //1 cout << get<0>(x);  //2 

2 works. 1 does not.

Why is it so?

From Lounge C++ I learnt that it is probably because the compiler does not know what data type is stored at that index. But it did not make much sense to me as the compiler could just look up the declaration of that tuple and determine the data type or do whatever else is done while accessing other data structures' elements by index.

like image 200
anukul Avatar asked Sep 16 '15 10:09

anukul


People also ask

Can you access tuple by index?

Because each item in a Python tuple has a corresponding index number, we're able to access items. In addition to positive index numbers, we can also access items from the tuple with a negative index number, by counting backwards from the end of the tuple, starting at -1 .

Do tuples have indexes?

Each item in a tuple has a unique index value, starting with zero. Index values continue in increments of one. You can access an individual item in a tuple by referencing the item's index value.


1 Answers

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) 
like image 107
galinette Avatar answered Sep 19 '22 08:09

galinette