std::ignore 使用结构化绑定?

std::ignore with structured bindings?

序曲:

std::tuple<int, int, int> f();
std::tuple<int, int, float, int> g();

C++1z 将引入结构化绑定的语法,这将使编写而不是

成为可能
int a, b, c;
std::tie(a, b, c) = f();

类似

auto [a, b, c] = f();

然而,std::tie 也允许指定 std::ignore 忽略某些组件,例如:

std::tie(a, b, std::ignore, c) = g();

是否可以使用新的结构化绑定语法做类似的事情?它是如何工作的?

Will it be possible to do something similar using the new structured bindings syntax?

没有。你只需要补一个变量名,后面就不说了。

结构化绑定提案包含专门的部分来回答您的问题 (P0144R2):

3.8 Should there be a way to explicitly ignore components?

The motivation would be to silence compiler warnings about unused names. We think the answer should be “not yet.” This is not motivated by use cases (silencing compiler warnings is a motivation, but it is not a use case per se), and is best left until we can revisit this in the context of a more general pattern matching proposal where this should fall out as a special case.

Symmetry with std::tie would suggest using something like a std::ignore:

tuple<T1,T2,T3> f();

auto [x, std::ignore, z] = f(); // NOT proposed: ignore second element

However, this feels awkward.

Anticipating pattern matching in the language could suggest a wildcard like _ or *, but since we do not yet have pattern matching it is premature to pick a syntax that we know will be compatible. This is a pure extension that can wait to be considered with pattern matching.

但是请注意,该标准的工作草案目前正在由相关国家机构 (NB) 进行修订,并且有一个 NB 评论要求此功能 (P0488R0, US100):

Decomposition declarations should provide syntax to discard some of the returned values, just as std::tie uses std::ignore.

我通常使用 _,它是 C++ 中的有效标识符,但看起来与例如 Kotlin 的下划线运算符相同,它会丢弃 lambda 参数。 你最终会得到一个像这样的好代码……

map([&](auto it) {
    auto [_, deviceServiceXAddr] = it;
    return deviceServiceXAddr;
});