Why std::unique_ptr does not permit type inference?

自古美人都是妖i 提交于 2019-12-30 03:55:28

问题


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?


回答1:


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.


In C++17 you will be able to write:

auto foo2 = std::unique_ptr(new Foo());

thanks to class template deduction - assuming P0433R0 is accepted, which adds a deduction guide to 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 if that type exists, otherwise T*. Must satisfy NullablePointer.

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

Which would enable class template deduction for std::unique_ptr.



来源:https://stackoverflow.com/questions/41162868/why-stdunique-ptr-does-not-permit-type-inference

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!