c++ - 结构化绑定(bind)声明示例中的 if-with-initializer 格式错误?

标签 c++ c++17

我正在阅读 Structured binding declaration on cppreference.com

在看到底部的最后一个示例之前,我认为我已经很好地理解了这些示例。

#include <set>
#include <string>
#include <iomanip>
#include <iostream>

int main() {
    std::set<std::string> myset;
    
    if (auto [iter, success] = myset.insert("Hello"); success) 
        std::cout << "insert is successful. The value is " << 
        std::quoted(*iter) << '\n';
    else
        std::cout << "The value " << std::quoted(*iter) << " already 
        exists in the set\n";
}

初看还行,越看越看不懂if子句。

在顶部列出了可能的形式:

attr(optional) cv-auto ref-operator(optional) [ identifier-list ] = expression ; (1)

attr(optional) cv-auto ref-operator(optional) [ identifier-list ] { expression } ; (2)

attr(optional) cv-auto ref-operator(optional) [ identifier-list ] ( expression ) ; (3)

对我来说,它看起来像是演绎类型 (1)。但这对我来说毫无意义,因为

expression - an expression that does not have the comma operator at the top level (grammatically, an assignment-expression), and has either array or non-union class type. If expression refers to any of the names from identifier-list, the declaration is ill-formed.

表示如果表达式在标识符列表中,则声明格式错误。所以在我看来,成功不是表达的一部分。如果是这样的话,那么

auto [iter, success] = myset.insert("Hello");

只会将插入的 "Hello" 分配给 iter 并且 success 会是什么?!?反之则会违反表达式部分。但它显然可以编译和运行,所以我一定是遗漏了什么

最佳答案

which says that the declaration is ill formed if the expression is in the identifier list

不是这么说的。它表示如果表达式 使用标识符列表 中的任何名称,则它是错误格式的。 myset.insert("Hello")不这样做所以没关系。

std::set::insert返回 std::pair<std::set::iterator, bool> std::set::iterator在哪里标记元素位置和 bool指示是否已插入。所以auto [iter, success] = myset.insert("Hello")捕获该对并设置 iterstd::set::iteratorsuccessbool .

关于c++ - 结构化绑定(bind)声明示例中的 if-with-initializer 格式错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53787312/

相关文章:

c++ std::bad_alloc on std::filesystem::path 追加

c++ - 充分利用 static_assert 和 std::is_invocable

c++ - 如何在概念中使用 C++ requires 子句来要求成员变量满足概念约束?

C++17 单独的显式方法模板实例化声明和定义

c++ - 有没有办法拥有模板的别名并保留类模板参数推导?

c++ - C++ 中的 Protobuf ParseDelimitedFrom 实现

c++ - Netbeans C++ MinGW 设置

c++ - 使用 std::async 调用采用 unique_ptr 的函数

c++ - C/C++ 中最好的加密库是什么?

c++ - 我可以在没有 C++ 的情况下学习 Win32 API(仅使用 C)吗?