C ++当模板参数扣除失败时 [英] C++ When template argument deduction fails
问题描述
为什么C ++不能确定我打算用这个语法创建一个 unique_ptr< A>
(a之前已声明为 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());
看起来非常多余的必须包括< A>
。对于大多数我使用的函数模板,为什么不使用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
对象应该直接取得动态分配的对象的所有权,所以不应该需要这个。您的代码应该写成:
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
调用 reset()
可以使用:
or, if a
already exists, a call to reset()
can be used:
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屋!