为什么编译器需要指定类型?
Why does the compiler require the type to be specified?
我已经实现了一个负责构造单个类型的类模板(遵循构建器模式(。构建器的构造函数用于推断两种类型。
下面是演示问题的示例(使用编译器资源管理器(。我将 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。该程序有效。
相关文章:
- 我收到同义重复编译器错误。我应该如何修复"类型"X"的参数与类型"X"的参数不兼容?
- 从类型列表中递归删除重复项会导致编译器堆空间错误 (VS2017)
- 如果可推导类型上有替换,可变参数模板类型推导会使编译器崩溃
- 在模板化成员函数的返回类型中使用 std::enable_if 时的编译器差异
- 使用typedef'ed返回类型声明友元函数时出现编译器错误
- 当类型适当的构造函数可用时,为什么一个编译器尝试使用已删除的副本构造函数
- 需要有关运行具有输入类型的编译器的帮助
- 编译器给出错误:format 指定类型 'float *',但参数的类型'double' [-Wformat]
- 如何告诉编译器名称是模板类型名称?
- 不同c++编译器之间的自动类型推导不匹配
- 编译器错误"在if语句中分配不兼容的类型"
- 如何在编译器时动态获取元组内的变量类型C++?
- 如果类在 C++ 中具有常量或引用类型的非静态数据成员,为什么编译器不提供默认赋值运算符?
- 如果条件取决于模板类型并且在编译时已知,是否可以保证C++编译器不会生成分支?
- 如何配置VS 2012的编译器来更改基本数据类型大小?
- 交叉编译器树莓派不完整类型,而本机编译器工作
- gcc 是否有编译指示来定义文件类型/编译器
- 基本操作数具有非指针类型 G++ 编译器错误
- 使用模板调用重载函数(未解析的重载函数类型编译器错误)
- 与我定义的类的成员有关的c++向量数据类型编译器错误问题