为什么std :: unique_ptr不允许类型推断? [英] Why does std::unique_ptr not permit type inference?

查看:91
本文介绍了为什么std :: unique_ptr不允许类型推断?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于模板参数的类型很明显,所以读/写示例的第二行会更容易:

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 :: 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:

std :: remove_reference< Deleter> :: type :: pointer (如果存在),否则为 T * .必须满足 NullablePointer .

std::remove_reference<Deleter>::type::pointer if that type exists, otherwise T*. Must satisfy NullablePointer.

类型别名(例如 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不允许类型推断?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆