问题描述
tuple <int, string, int> x=make_tuple(1, "anukul", 100);
cout << x[0]; //1
cout << get<0>(x); //2
2 作品.1 没有.
为什么会这样?
我从 Lounge C++ 了解到,这可能是因为编译器不知道该索引处存储的是什么数据类型.但这对我来说没有多大意义,因为编译器可以只查找该元组的声明并确定数据类型,或者在通过索引访问其他数据结构的元素时执行其他任何操作.
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.
推荐答案
因为 [] 是一个运算符(名为 operator[]
),因此是一个成员函数,并在运行时被调用.
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.
为了更好地理解,元组可能存储不同的类型.模板函数可能会根据传递的索引返回不同的类型,因为这是在编译时解决的.无论传递的参数的值是什么,operator[] 都必须返回唯一的类型.因此元组功能无法实现.
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(x)
和 get(x)
是编译时生成的两个不同的函数,返回不同的类型.编译器实际上生成了两个函数,它们将被重整为类似
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)
和
string get_tuple_int_string_int_1(x)
这篇关于为什么我们不能通过索引访问元组的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!