C ++ 17:打开元组时仅保留一些成员 [英] C++17: Keep only some members when tuple unpacking
问题描述
假设您需要调用以下方法:
Let's imagine you need to call the following method:
std::tuple<int, int, int> foo();
在C ++ 17中,您可以调用该函数并在一行中解压缩元组: / p>
In C++17, you can call the function and unpack the tuple in a single line:
auto [a, b, c] = foo();
现在,我如何继续仅存储 b
和 c
并丢弃 a
?
Now, how can I proceed to store only b
and c
and to discard a
?
目前,我只知道两个选择:
Currently, I'm only aware of two options:
1-自动解压缩时可以使用哑变量
1 - I can use a dummy variable when auto-unpacking
但是,哑变量将不被使用,并且会发出警告,因此,如果我想让警告保持沉默,该代码将非常令人讨厌:
However, the dummy variable will be unused and it will issue a warning, so if I want to silent that warning the code will be quite unpleasant to see:
#pragma warning(push)
#pragma warning(disable:4101)
// ReSharper disable once CppDeclaratorNeverUsed
auto [_, b, c] = foo();
#pragma warning(pop)
2-我可以存储整个元组,并使用 std :: get
检索对我唯一需要的变量的引用。该代码不太令人讨厌,但语法也不太简单。
2 - I can store the whole tuple and use std::get
to retrieve the reference to the only variables I need. The code is less unpleasant but the syntax is also less straightforward.
此外,对于每个要保存在元组中的新值,此代码的大小都增加一行。 / p>
Moreover, this code's size increases by one line for each new value that we want keep in the tuple.
auto tuple = foo();
int b = std::get<1>(tuple);
int c = std::get<2>(tuple);
是否还有另一种更简单的方法仅解压缩元组中的某些参数?
推荐答案
另一种替代方法是使用 std :: tie
:
Another alternative is to use an std::tie
:
int b, c;
std::tie(std::ignore, b, c) = foo();
编辑
如评论中所述,这种方法存在一些问题:
As mentioned in the comments, there are some issues with this approach:
- 不可能进行类型推断
- 必须先构造对象,所以除非默认构造函数很简单,否则它不是一个好的选择。
这篇关于C ++ 17:打开元组时仅保留一些成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!