Why does std::unique_ptr not permit type inference?
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, otherwiseT*
. Must satisfyNullablePointer
.
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
.