下面的代码不能在使用 -std=c++17
的 GCC 11 上编译,但可以使用 -std=c++20
:
#include <iostream>
#include <string>
struct Foo {
std::string s;
int i;
};
int main()
{
Foo foo("hello", 42);
std::cout << foo.s << ' ' << foo.i << '\n';
}
C++20 中有什么功能可以实现这一点?编译器生成什么样的构造函数?
最佳答案
这里使用的 C++20 特性是 initialization of aggregates from parenthesis (P0960R3) :
This paper proposes allowing initializing aggregates from a parenthesized list of values; that is,
Aggr(val1, val2)
would mean the same thing asAggr{val1, val2}
, except that narrowing conversions are allowed.
这是来自上面链接的示例:
struct A {
int a;
int&& r;
};
int f();
int n = 10;
A a1{1, f()}; // OK, lifetime is extended
A a2(1, f()); // well-formed, but dangling reference
A a3{1.0, 1}; // error: narrowing conversion
A a4(1.0, 1); // well-formed, but dangling reference
A a5(1.0, std::move(n)); // OK
因此,为了使您的代码适用于 C++17,只需将圆括号替换为大括号即可。
#include <iostream>
#include <string>
struct Foo {
std::string s;
int i;
};
int main()
{
Foo foo{"hello", 42};
std::cout << foo.s << ' ' << foo.i << '\n';
}
https://stackoverflow.com/questions/69331785/