复制初始化的默认模板参数推导

Default template argument deduction for copy initialization

C++17 有 class template argument deduction。但是,我想知道它是否适用于 auto x = X() 之类的语句,其中 X 是 class 模板。考虑这段代码:

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
}

这里是godbolt link。那么哪个编译器是正确的,这个程序是否有效 C++17?

这是 GCC 中的错误。

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

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

这不是 class 模板参数推导,因为没有模板参数被推导。 Class 模板参数推导应该允许省略模板大括号。在这种情况下使用 (){} 应该与它们是否被推导无关。