我正在研究 C++0x。当我看着 tuple我看到了这个例子。为什么我需要做 get<3>(var)
?为什么我不能做 var.get(index)
或 var.get<index>()
?我更喜欢这些以使代码看起来和感觉一致。
typedef tuple< int, double, long &, const char * > test_tuple ;
long lengthy = 12 ;
test_tuple proof( 18, 6.5, lengthy, "Ciao!" ) ;
lengthy = get<0>(proof) ; // Assign to 'lengthy' the value 18.
get<3>(proof) = " Beautiful!" ; // Modify the tuple’s fourth element.
最佳答案
你必须使用 get<0>
因为元组的每个成员都有不同的类型。因此 get<0>
的结果类型是int
, get<1>
是double
, get<2>
是long&
等。调用 get(0)
时无法实现此目的。因为它必须有一个固定的返回类型。
您可能还想看看模板元编程,因为这种模式是整个编程部分的基本模式之一。
http://en.wikipedia.org/wiki/Template_metaprogramming
http://www.boost.org/doc/libs/1_43_0/libs/mpl/doc/index.html
关于c++ - 为什么我不能执行 tupleVar.get(3) 或 .get<3>()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3372260/