C ++模板时参数推导失败 [英] C++ When template argument deduction fails
问题描述
为什么不能用C ++确定,我打算创建一个的unique_ptr< A>
这个语法? (一个具有previously被宣布为的unique_ptr< A>
)
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());
这似乎非常多余必须包括&LT; A&GT;
。这适用于我用,为什么不的unique_ptr?
It seems awfully redundant to have to include <A>
. This works for most functions templates I use, why not unique_ptr?
编辑: C ++现在支持make_unique,没有冗余
C++ now supports make_unique, with no redundancy.
推荐答案
的std ::的unique_ptr
是类的模板,而不是一个功能的模板。参数推导仅发生于的功能的模板,没有的类的模板。
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:
template <typename T>
std::unique_ptr<T> make_unique_ptr(T* ptr)
{
return std::unique_ptr<T>(ptr);
}
有关的std ::的unique_ptr
,不过,我会避免这样做:一个的std ::的unique_ptr
对象应直接采取动态分配对象的所有权,所以不应该有需要这一点。您code要么写为:
For std::unique_ptr
, though, I'd avoid doing this: a std::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:
std::unique_ptr<A> a(new A());
或者,如果 A
已经存在,到的调用复位()
可以用:
a.reset(new A());
至于为什么类型推演不会为实例化一个类模板时,请考虑下面的例子:
As for why type deduction won't work for instantiating a class template, consider the following example:
template <typename T>
struct X
{
template <typename U> X(U) { }
};
有没有办法, T
可以从构造函数的调用推断。即使是在简单的情况下,有型 T
,还有可麻烦,因为构造函数可以被重载。一个参数的构造函数
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 type T
, there can still be trouble since constructors can be overloaded.
这篇关于C ++模板时参数推导失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!