【问题标题】:Getting reference to the elements of a tuple获取对元组元素的引用
【发布时间】:2018-03-21 02:46:52
【问题描述】:

假设我有一个包含 ABC 类型的元组:

std::tuple<A,B,C> t;

如何提取对其元素之一的引用,即可变引用,以便我可以修改它?

std::get 返回一个副本。

【问题讨论】:

  • std::get 确实返回了一个引用。你试过std::get&lt;0&gt;t = A{};吗?您获得副本的唯一原因可能是因为您尝试将其分配给非引用变量。
  • @patatahooligan 感谢您的帮助,您可以将此作为答案发布吗?

标签: c++ reference stl tuples


【解决方案1】:

与您在 OP 中所说的相反,std::get 返回一个引用。事实上,它甚至有一个tuple&amp;&amp; 的重载,它返回一个T&amp;&amp;。您的误解可能源于您在导致副本的表达式中使用它。一个值得注意的例子是auto,它被设计为默认不声明引用。看看下面的代码。

std::tuple<int, int> my_tuple;

// Declare an int whose value is copied from the first member of the tuple
auto my_int = get<0>(my_tuple);

// Get a reference to it instead
auto& my_int_ref = std::get<0>(my_tuple);
my_int_ref = 0;    // Assign 0 to the first element

// Direct use inside an expression also works.
std::get<0>(my_tuple) = 1;    // Assign 1 to the first element.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-26
    • 2013-01-26
    • 2011-06-27
    • 2017-05-25
    • 1970-01-01
    • 2022-12-09
    • 1970-01-01
    相关资源
    最近更新 更多