我实现了一个类模板,该类模板负责构造单个类型(遵循构建器模式)。构建器的构造函数用于推导两种类型。
下面是一个演示该问题的示例(使用编译器资源管理器)。我将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> …Run Code Online (Sandbox Code Playgroud) 鉴于以下情况:
struct S
{
int x;
int& y;
};
int main()
{
int i = 6;
const S s{5, i}; // (1)
// s.x = 10; // (2)
s.y = 99; // (3)
}
Run Code Online (Sandbox Code Playgroud)
为什么什么时候(3)允许?sconst
(2)产生编译器错误,这是预期的。我预计也会(3)导致编译器错误。