将结构化绑定与基于范围的 for 循环与 (C++20) 初始化语句相结合
从 C++20 开始,您可以使用 range-based for loop 初始化语句,您可以将其与 structured bindings 组合如下:
#include <ios>
#include <iostream>
#include <string>
#include <string_view>
#include <utility>
bool foo(std::string_view s) {
return s == "b";
}
int main() {
bool a{false}, b{false}, c{false};
std::string string_a{"a"}, string_b{"b"}, string_c{"c"};
for (typedef std::pair<bool&, std::string_view> P;
auto [res, str] : {P{a, string_a}, {b, string_b}, {c, string_c}}) {
res = foo(str);
}
std::cout << std::boolalpha << a << " " << b << " " << c << "\n";
// false true false
}
利用typedef declarations are init-statements(其中没有alias-declarations)这一事实来声明P 实用程序别名,该别名又用于在初始化列表中进行类型推导基于 for 循环迭代(并绑定值)。
在 C++20 之前,您可以简单地将实用程序类型别名放在循环之前:
using P = std::pair<bool&, std::string_view>;
for (auto [res, str] : {P{a, string_a}, {b, string_b}, {c, string_c}}) {
res = foo(str);
}
或完全删除实用程序类型别名:
for (auto [res, str] : {
std::pair<bool&, std::string_view>{a, string_a},
{b, string_b}, {c, string_c}}) {
res = foo(str);
}
这样的技巧被认为是一种好的做法吗?
这部分答案可能会进入基于意见的领域,虽然这不一定适用于上面的 sn-p,但它肯定适用于使用的技术 in the answer you refer to ("Hckety hack hack")。句法组合非常聪明,以至于最终被称为“技巧”,可能最终过于聪明而对自己的利益不利,并且阻碍了代码库的清晰度和理解,对于特定的作者代码以及其他(当前和未来)维护者。