副本初始化的默认模板参数推导

Default template argument deduction for copy initialization

本文关键字:参数 初始化 默认 副本      更新时间:2023-10-16

C++17 具有类模板参数推导。但是,我想知道它是否适用于像auto x = X()这样的语句,其中X是一个类模板。请考虑以下代码:

template <typename T = void>
struct X {};
int main() {       // all with -std=c++17
X<> x0;        // compiles in both clang and gcc
X x1;          // compiles in both clang and gcc
auto x2 = X(); // compiles in clang but not gcc
X<> x3 = X();  // compiles in clang but not gcc
}

这是神螺栓链接。那么哪个编译器是正确的,这个程序是否有效C++17?

这是GCC中的一个错误。

请注意,如果将括号替换为大括号,代码将编译:

auto x2 = X{}; // now compiles in clang and gcc
X<> x3 = X{}; // now compiles in clang and gcc

这不是类模板参数推导,因为没有推导模板参数。类模板参数推导应允许省略模板大括号。在这种情况下,使用(){}不应与是否推断

它们无关。