问题描述
由于模板参数的类型很明显,所以读/写示例的第二行会更容易:
It would be easier to read/write the second line of my example since the type of the template argument is obvious:
#include <memory>
struct Foo{};
int main()
{
// redundant: good
auto foo1 = std::unique_ptr<Foo>(new Foo());
// without explicitness: does not compile
auto foo2 = std::unique_ptr(new Foo());
}
当然,如果您想使用多态性,我们总是可以这样写:
Of course, if you want to use polymorphism, we could always write:
auto base = std::unique_ptr<Base>(new Derived());
产生这种约束的原因是什么?
What is the reason for such a constraint?
推荐答案
这不是 std :: unique_ptr
-模板类的实例化不会自动从C ++ 17之前的构造函数中推断出类型.这就是为什么诸如 std :: make_unique
, std :: make_pair
和 std :: make_tuple
存在:它们使用模板函数参数推论,以减少样板.
This is not an issue that's... unique to std::unique_ptr
- instantiation of template classes does not automatically deduce the types from the constructors previous to C++17. This is why facilities such as std::make_unique
, std::make_pair
and std::make_tuple
exist: they use template function argument deduction to reduce boilerplate.
在C ++ 17中,您将能够编写:
In C++17 you will be able to write:
auto foo2 = std::unique_ptr(new Foo());
感谢 类模板推导 -假设 P0433R0 被接受,这会添加一个推理指南到 std :: unique_ptr
.
thanks to class template deduction - assuming P0433R0 is accepted, which adds a deduction guide to std::unique_ptr
.
需要扣除指南,因为 std :: unique_ptr
的采用原始指针的构造器使用 pointer
类型别名,其定义如下:
The deduction guide is required because std::unique_ptr
's constructor that takes a raw pointer uses the pointer
type alias which is defined as follows:
类型别名(例如 pointer
)是不可推论的上下文,因此P0433R0建议添加以下内容:
Type aliases like pointer
are non-deducible contexts, so P0433R0 proposes the addition of:
template<class T> unique_ptr(T*)
-> unique_ptr<T, default_delete<T>>;
template<class T, class V> unique_ptr(T*, V)
-> unique_ptr<T, default_delete<T, V>>;
template<class U, class V> unique_ptr(U, V)
-> unique_ptr<typename pointer_traits<typename V::pointer>::element_type, V>;
哪些将为 std :: unique_ptr
启用类模板推论.
这篇关于为什么std :: unique_ptr不允许类型推断?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!