clang vs gcc - 从模板参数派生的结构的 CTAD

Vit*_*meo 3 c++ language-lawyer c++20 ctad deduction-guide

考虑以下代码:

template <typename B>
struct D : B { };

D d{[]{ }};
Run Code Online (Sandbox Code Playgroud)
  • gcc 12.x 接受它并推断出结果与预期d一致D</* type of lambda */>

  • clang 14.x 拒绝它并出现以下错误:

<source>:4:3: error: no viable constructor 
              or deduction guide for deduction of template arguments of 'D'
D d{[]{ }};
  ^

<source>:2:8: note: candidate template ignored: 
              could not match 'D<B>' against '(lambda at <source>:4:5)'
struct D : B { };
       ^

<source>:2:8: note: candidate function template not viable: 
              requires 0 arguments, but 1 was provided
Run Code Online (Sandbox Code Playgroud)

godbolt.org 上的实例


哪个编译器在这里表现正确?

cig*_*ien 8

代码片段中并没有提供推演指导。P1816通过要求生成聚合推导候选,添加了 C++20 中聚合类模板的推导指南

代码是有效的,但 Clang还不支持 P1816

添加推导指南也可以在 Clang 中编译。

template <typename B> D(B) -> D<B>;
Run Code Online (Sandbox Code Playgroud)