【问题标题】:Why can't I do tupleVar.get(3) or .get<3>()?为什么我不能执行 tupleVar.get(3) 或 .get<3>()?
【发布时间】:2010-07-30 14:09:41
【问题描述】:

我正在研究 C++0x。当我查看tuple 时,我看到了这个例子。为什么我需要做get&lt;3&gt;(var)?为什么我不能var.get(index)var.get&lt;index&gt;()?我更喜欢这些以使代码看起来和感觉一致。

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.

【问题讨论】:

    标签: c++ c++11 tuples


    【解决方案1】:

    您必须使用get&lt;0&gt;,因为元组的每个成员都有不同的类型。因此get&lt;0&gt; 的结果类型为intget&lt;1&gt;doubleget&lt;2&gt;long&amp; 等。调用get(0) 时无法实现这一点,因为它必须具有固定的返回类型。

    您可能还想看看模板元编程,因为这种模式是整个编程部分的基本模式之一。

    http://en.wikipedia.org/wiki/Template_metaprogramming
    http://www.boost.org/doc/libs/1_43_0/libs/mpl/doc/index.html

    【讨论】:

    • 哦是的...我完全忘记了。我知道我的 C++ 生锈了。感谢您的重大提醒。
    • 当然,您可以在 Python 中编写 var[3] 的原因是它是一种动态类型语言。
    猜你喜欢
    • 2012-02-04
    • 2014-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-14
    • 2021-09-25
    • 2020-08-09
    相关资源
    最近更新 更多