为什么std :: unique_ptr不允许类型推断? [英] Why std::unique_ptr does not permit type inference?
问题描述
全部在标题中。读/写我的示例的第二行会更容易,因为模板参数的类型很明显:
All is in the title. 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 of such a constraint?
推荐答案
这不是...对于 std :: unique_ptr
-模板类的实例化不会自动从C ++之前的构造函数中推断出类型17。这就是为什么诸如 std :: make_unique
, std :: make_pair
和 std :: make_tuple
存在:它们使用 template函数自变量推导来减少样板。
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
的构造函数使用原始指针使用指针
类型别名,其定义如下:
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:
std :: remove_reference< Deleter> :: type :: pointer
(如果存在),否则为T *
。必须满足NullablePointer
。
std::remove_reference<Deleter>::type::pointer
if that type exists, otherwiseT*
. Must satisfyNullablePointer
.
键入别名,如 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
。
Which would enable class template deduction for std::unique_ptr
.
这篇关于为什么std :: unique_ptr不允许类型推断?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!