【问题标题】:Template argument deduction in case of designated initializers in C++在 C++ 中指定初始值设定项的情况下的模板参数推导
【发布时间】:2021-12-25 13:39:34
【问题描述】:

在下面的代码中,有一个 A<T> 对象的初始化,模板参数推导使用指定的初始化器以两种稍微不同的形式:

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

int main() {
   A a{.t=1};   //#1: ok in GCC and MSVC
   A b{.t={1}}; //#2: ok in MSVC only
}

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

error: class template argument deduction failed:
error: no matching function for call to 'A(<brace-enclosed initializer list>)'

演示:https://gcc.godbolt.org/z/PaEaMjM7q

哪个编译器在那里?

【问题讨论】:

    标签: c++ templates language-lawyer c++20 aggregate-initialization


    【解决方案1】:

    GCC 是正确的。像 {1} 这样的 Braced-init-list 没有类型,所以它使 template argument deduction 失败。

    非推断上下文

    ...

    参数P,其A为a braced-init-list, but P is not std::initializer_list, a reference to one (possibly cv-qualified), or (since C++17)对数组的引用:

    【讨论】:

      猜你喜欢
      • 2022-11-20
      • 2017-03-07
      • 2013-04-26
      • 2020-01-13
      • 2020-07-20
      • 2020-01-13
      • 2019-03-27
      • 1970-01-01
      • 2016-05-15
      相关资源
      最近更新 更多