C++ 中聚合的带括号初始化的模板参数推导

Fed*_*dor 8 c++ language-lawyer aggregate-initialization c++20

在下面的代码中,使用模板参数推导来初始化A<T>对象,使用两种形式(根据大括号的类型不同):

template<typename T>
struct A{ T x; };

int main() {
    static_assert( A{1}.x == 1 ); //#1: ok in GCC and MSVC
    static_assert( A(1).x == 1 ); //#2: ok in GCC only
}
Run Code Online (Sandbox Code Playgroud)

第一种方式被 GCC 和 MSVC 接受,而第二种方式仅适用于 GCC,而 MSVC 打印错误:

error C2641: cannot deduce template arguments for 'A'
error C2780: 'A<T> A(void)': expects 0 arguments - 1 provided
error C2784: 'A<T> A(A<T>)': could not deduce template argument for 'A<T>' from 'int'
Run Code Online (Sandbox Code Playgroud)

演示: https: //gcc.godbolt.org/z/97G1acqPr

这是 MSVC 中的错误吗?

dfr*_*fri 6

这是 MSVC 中的一个错误。

以下论文均是C++20中介绍的:

虽然 MSVC 将它们全部列出为通过 Visual Studio 版本页面在其 Microsoft C/C++ 语言一致性中实现的,但似乎他们已经正确地单独实现了它们

// OK (P0960R3, P1975R0)
struct A { int x; };
A a(1);

// OK (P2131R0)
template<typename T>
struct B { T x; };
B b{1};

// rejects-invalid (allowed by the union of the papers)
template<typename T>
struct C { T x; };
C c(1);
Run Code Online (Sandbox Code Playgroud)

MSVC 似乎错过了实现论文联合的机会。但是,我还没有找到开放的错误报告。

  • 谢谢,我提交了 MSVC bug:https://developercommunity.visualstudio.com/t/Template-argument-deduction-fails-in-cas/1584263 (2认同)