C++当模板参数推导失败时
为什么 C++ 无法确定我打算使用此语法创建 unique_ptr
? (a 之前已被声明为 unique_ptr
)
a = unique_ptr(new A());
必须包含 似乎非常多余。这适用于我使用的大多数函数模板,为什么 unique_ptr 不适用呢?
编辑: C++ 现在支持 make_unique,没有冗余。
Why can't C++ determine that I intend to create a unique_ptr<A>
with this syntax? (a has previously been declared as unique_ptr<A>
)
a = unique_ptr(new A());
It seems awfully redundant to have to include <A>
. This works for most functions templates I use, why not unique_ptr?
EDIT: C++ now supports make_unique, with no redundancy.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
std::unique_ptr
是一个类模板,而不是函数模板。参数推导仅发生在函数模板上,而不发生在类模板上。一个常用的技巧是编写一个函数模板来创建实例化类模板类型的对象,例如:
对于
std::unique_ptr
,不过,我会避免这样做:astd::unique_ptr
对象应该直接获取动态分配对象的所有权,因此不需要这样做。您的代码应该写为:或者,如果
a
已经存在,则可以使用对reset()
的调用:至于为什么类型推导不适用于实例化类模板,请考虑以下示例:
无法从构造函数的调用中推导出
T
。即使在“更简单”的情况下,存在带有T
类型参数的构造函数,仍然可能会出现问题,因为构造函数可以重载。std::unique_ptr
is a class template, not a function template. Argument deduction only happens for function templates, not class templates.A commonly used trick is to write a function template that creates an object of the instantiated class template type, for example:
For
std::unique_ptr
, though, I'd avoid doing this: astd::unique_ptr
object should directly take ownership of the dynamically allocated object, so there should not be a need for this. Your code should either be written as:or, if
a
already exists, a call toreset()
can be used:As for why type deduction won't work for instantiating a class template, consider the following example:
There is no way that
T
could be deduced from an invocation of the constructor. Even in "simpler" cases where there is a constructor with a parameter of typeT
, there can still be trouble since constructors can be overloaded.