【发布时间】:2019-08-18 22:32:15
【问题描述】:
我已经实现了一个类模板,它负责构造单一类型(遵循构建器模式)。 builder的构造函数用于推导两种类型。
下面是一个演示问题的示例(使用编译器资源管理器)。我在 -std=c++17 中使用了 clang 6。
#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?
-
我的意思是编译器资源管理器可以用来演示错误。我已经更新了帖子以清除它。
标签: c++ templates c++17 type-deduction