【发布时间】:2019-04-21 22:40:29
【问题描述】:
我是 C++ 模板的新手,我(非常不成功)试图强制编译器在初始化时推断模板类型名参数。
这是我的代码。
template <typename T>
class C
{
public:
T a;
C(T a) : a(a) {}
C(const C<T>& other) : a(other.a) {}
};
int main()
{
C<int> x(1);
C y{ x };
return 0;
}
这段代码用g++编译会报错。
test.cpp:13:11: error: missing template arguments before ‘y’
C y{ x };
^
我想保持这种语法 - 只是 C 没有明确指定模板参数。
我曾尝试使用演绎指南,但它只引发了另一个错误。
template <typename T> C(const C<T>& other) -> C<T>;
当我在 C 类的定义下方插入这一行时,我得到了这个。
test.cpp:10:51: error: expected constructor, destructor, or type conversion before ‘;’ token
template <typename T> C(const C<T>& other) -> C<T>;
^
当我将此行放入 C 类定义(在顶部)中时发生另一个错误。
C(const C<T>& other) -> C<T>;
test.cpp:4:26: error: ‘C’ function with trailing return type not declared with ‘auto’ type specifier
C(const C<T>& other) -> C<T>;
^~~~
在这两种情况下,第一次提及错误仍然存在。
谢谢!
【问题讨论】:
-
无法重现:我使用 g++ (8.3.0) 和 clang++ (7.0.1) 编译您的原始代码,没有错误。您确定您已启用 C++17 编译吗?阅读错误消息,我怀疑您正在编译 C++14 或 C++11,并且在 C++17 中引入了推导指南。
-
谢谢。我的错误 - 我一直在使用 g++ 8.2.0,默认情况下它是 C++14。它适用于 C++17。
标签: c++ templates type-deduction