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?
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 asstd::make_unique
,std::make_pair
andstd::make_tuple
exist: they use template function argument deduction to reduce boilerplate.In C++17 you will be able to write:
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 thepointer
type alias which is defined as follows:Type aliases like
pointer
are non-deducible contexts, so P0433R0 proposes the addition of:Which would enable class template deduction for
std::unique_ptr
.