【问题标题】:Why can't GCC compiler deduce one of the template parameter from std::array in alias template form为什么 GCC 编译器不能以别名模板形式从 std::array 推导出模板参数之一
【发布时间】:2021-12-28 09:58:27
【问题描述】:

在 C++20 中,如果应用别名模板,则可以有隐式推导指南。

然后,我构造了一个简单的模板别名,即ints

template <std::size_t N>
using ints = std::array<int, N>;

但是:

ints{1, 2, 3, 4}

不起作用,GCC说:

  • 错误:没有匹配函数调用array(int, int, int, int)
  • 注意:无法推导出模板参数N
  • 注意:std::array&lt;int, N&gt;int 的类型不匹配

我不明白为什么编译失败。

还有:

template <typename T>
using array_of_4 = std::array<T, 4>;

array_of_4{1, 2, 3, 4}

也不行。

  • 是不是因为std::array的推演指南是用户提供的?
  • 如果上面的回答不正确,那是什么原因呢?

我发现了一个关于这个问题的类似问题:How to write deduction guidelines for aliases of aggregate templates?

由此得出结论,按照标准,这段代码应该是格式良好的。因此,GCC 可能有不同的实现来阻止此代码编译。

【问题讨论】:

  • clang 的错误是:error: alias template 'ints' requires template arguments; argument deduction only allowed for class templates.
  • clang 还不支持别名模板的 CTAD (en.cppreference.com/w/cpp/20)

标签: c++ language-lawyer c++20 template-aliases ctad


【解决方案1】:
ints{1, 2, 3, 4}

我不明白为什么编译失败。

您没有指定模板参数。这有效:

ints<4>{1, 2, 3, 4}

array_of_4{1, 2, 3, 4}

也不行。

同样的问题。这有效:

array_of_4<int>{1, 2, 3, 4}

std::array的推演指南是用户提供的?

是的。

【讨论】:

  • 那么,在这种情况下,这会破坏 CTAD 的目的吗?我不确定
  • @DesmondGold “打败 CTAD 的目的”是什么意思?
  • 我认为问题是为什么std::array a {1, 2, 3, 4}; 有效,但ints a {1, 2, 3, 4}; 无效?在这两种情况下,编译器都应该能够将类型推断为std::array&lt;int,4&gt;
猜你喜欢
  • 1970-01-01
  • 2014-12-27
  • 2012-02-21
  • 1970-01-01
  • 2011-08-28
  • 1970-01-01
  • 1970-01-01
  • 2012-03-26
相关资源
最近更新 更多