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

Kor*_*ory 3 c++ templates type-deduction c++17

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

下面是一个演示该问题的示例(使用编译器资源管理器)。我将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();
}
Run Code Online (Sandbox Code Playgroud)

这是我收到的错误消息。


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
Run Code Online (Sandbox Code Playgroud)

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

  • 使用功能模板(例如make_builder(...)
  • 给建造者起个名字(例如builder b{...}
  • 指定模板参数(例如builder<T>{...}

我仍然想知道编译器会发生什么变化?编译器无法推断出类型吗?C ++ 17支持这一点,对吧?

Bar*_*rry 7

这是c虫41450。该程序有效。