C++20 标准引入了 Designated Initializer。它类似 C# 的 Object Initializer 和 Kotlin 的 apply(scope function),允许在仅需要初始化类或结构体的部分成员时,使用更少的代码即可完成。
#include int main() {struct point {double x &#61; 0, y &#61; 0, z &#61; 0;};struct line_segment {struct point s, t;};const auto print_point &#61; [](const point& p) {std::cout << "<" << p.x << ", " << p.y << ", " << p.z << ">" << std::endl;};const struct point p{ .x &#61; 1, .y &#61; 2, };const struct line_segment s { .s{}, .t{.z &#61; 1} }; print_point(p);print_point(s.s);print_point(s.t);return 0;
}