具有聚合类型的自动模板推导 C++20
Automatic template deduction C++20 with aggregate type
我对这段 C++ 代码感到困惑:
template <class T>
struct Foo {
T value;
};
int main() {
return Foo<int>(0).value;
// Below code works as well in gcc
// return Foo(0).value;
}
它在 C++20 标准(但不是 C++17 标准)和最新的 MSVC 中使用 GCC 10 编译,但即使在 C++20 中也不使用 clang 13 或 14。
根据标准(来自cppreference)至少在指定模板类型时应该可以实例化Foo
。
为什么这与 C++20 相关?我没有看到模板推导规范有任何变化(我可能漏掉了什么)。
此外(这很奇怪),C++20 模式下的 GCC 甚至在我们调用 Foo
而不指定模板化类型 (Foo(0)
) 时编译。
神箭linkhere
关于你的link,编译器会告诉你你的调用有什么问题:
error: no matching function for call to 'Foo::Foo(int)'
所以,问题是您尝试调用一个不存在的构造函数。您的 class Foo
只有默认构造函数 Foo()
。
只需将 return Foo<int>(0).value;
更改为 return Foo<int>().value;
即可。否则你需要一个像 Foo(T) {}
.
这样的构造函数
It compiles with GCC 10 in C++20 standard (but not in C++17 standard)
and latest MSVC.
这是因为 GCC 10 和最新的 MSVC 实现了 allow initializing aggregates from a parenthesized list of values,它允许我们使用 括号 来初始化聚合。
Also (this is strange), GCC in C++20 mode even compiles when we call
Foo without specifying templated type (Foo(0)
).
这是因为 GCC 10 实现了 class template argument deduction for aggregates,这使得 T
自动推导为 int
。
请注意,clang 目前未实现这两个 C++20 功能,因此您的代码无法被 clang 接受。
您可以参考cppreference了解当前编译器对C++20特性的支持。
我对这段 C++ 代码感到困惑:
template <class T>
struct Foo {
T value;
};
int main() {
return Foo<int>(0).value;
// Below code works as well in gcc
// return Foo(0).value;
}
它在 C++20 标准(但不是 C++17 标准)和最新的 MSVC 中使用 GCC 10 编译,但即使在 C++20 中也不使用 clang 13 或 14。
根据标准(来自cppreference)至少在指定模板类型时应该可以实例化Foo
。
为什么这与 C++20 相关?我没有看到模板推导规范有任何变化(我可能漏掉了什么)。
此外(这很奇怪),C++20 模式下的 GCC 甚至在我们调用 Foo
而不指定模板化类型 (Foo(0)
) 时编译。
神箭linkhere
关于你的link,编译器会告诉你你的调用有什么问题:
error: no matching function for call to 'Foo::Foo(int)'
所以,问题是您尝试调用一个不存在的构造函数。您的 class Foo
只有默认构造函数 Foo()
。
只需将 return Foo<int>(0).value;
更改为 return Foo<int>().value;
即可。否则你需要一个像 Foo(T) {}
.
It compiles with GCC 10 in C++20 standard (but not in C++17 standard) and latest MSVC.
这是因为 GCC 10 和最新的 MSVC 实现了 allow initializing aggregates from a parenthesized list of values,它允许我们使用 括号 来初始化聚合。
Also (this is strange), GCC in C++20 mode even compiles when we call Foo without specifying templated type (
Foo(0)
).
这是因为 GCC 10 实现了 class template argument deduction for aggregates,这使得 T
自动推导为 int
。
请注意,clang 目前未实现这两个 C++20 功能,因此您的代码无法被 clang 接受。
您可以参考cppreference了解当前编译器对C++20特性的支持。