问题描述
假设您需要调用以下方法:
Let's imagine you need to call the following method:
std::tuple<int, int, int> foo();
在 C++17 中,您可以在一行中调用函数并将元组解包:
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.
此外,对于我们希望在元组中保留的每个新值,此代码的大小会增加一行.
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
:
int b, c;
std::tie(std::ignore, b, c) = foo();
编辑
正如评论中提到的,这种方法存在一些问题:
As mentioned in the comments, there are some issues with this approach:
- 无法进行类型推断
- 对象必须在之前构造,所以除非默认构造函数是微不足道的,否则它不是一个好的选择.
这篇关于C++17:元组解包时只保留一些成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!