我正在阅读 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")
捕获该对并设置 iter
到 std::set::iterator
和 success
到 bool
.
关于c++ - 结构化绑定(bind)声明示例中的 if-with-initializer 格式错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53787312/