为什么编译器需要指定类型?

Why does the compiler require the type to be specified?

本文关键字:类型 编译器 为什么      更新时间:2023-10-16

我已经实现了一个负责构造单个类型的类模板(遵循构建器模式(。构建器的构造函数用于推断两种类型。

下面是演示问题的示例(使用编译器资源管理器(。我将 clang 6 与 -std=c++17 一起使用。

#include <utility>
template <typename T>
struct builder
{
explicit builder(T& _t);
auto option(int x) -> builder&;
auto build() -> int;
};
template <typename T>
void build_it(T& _t, int _u)
{
// Why does the line below not compile?
// C++17 compilers should be able to deduce the type, right?
auto obj = builder{_t}.option(_u).build();
}

这是我收到的错误消息。


x86-64 clang 6.0.0 (Editor #1, Compiler #1) C++
x86-64 clang 6.0.0
-std=c++17 -O2 -Wall -Wextra
1
<Compilation failed>
x86-64 clang 6.0.0 - 455ms
#1 with x86-64 clang 6.0.0
<source>:15:27: error: member reference base type 'builder' is not a structure or union
auto obj = builder{_t}.option(_u).build();
~~~~~~~~~~~^~~~~~~~~
1 error generated.
Compiler returned: 1

我通过以下方式解决了这个问题:

  • 使用函数模板(例如make_builder(...)(
  • 为构建器命名(例如builder b{...}(
  • 指定模板参数(例如builder<T>{...}(

我仍然想知道编译器对什么感到不安? 编译器不能推断出类型吗?C++17 支持这一点,对吧?

这是 clang bug 41450。该程序有效。

相关文章: