C++ Logo

std-discussion

Advanced search

Re: std::make_shared and type deduction

From: Ville Voutilainen <ville.voutilainen_at_[hidden]>
Date: Tue, 7 Jul 2020 23:51:51 +0300
On Tue, 7 Jul 2020 at 23:46, Jason McKesson via Std-Discussion
<std-discussion_at_[hidden]> wrote:
>
> On Tue, Jul 7, 2020 at 2:37 PM Kyle Knoepfel via Std-Discussion
> <std-discussion_at_[hidden]> wrote:
> >
> > I routinely encounter situations where objects must be owned by (smart) pointer, but the means in which the pointee is constructed is not under my control. For example:
> >
> > namespace external_library {
> > template <typename T>
> > Foo<T> make_foo();
> > }
> >
> > auto foo_ptr = std::make_unique<Foo<int>>(external_library::make_foo());
> >
> > In these circumstances, the required specification of Foo<Int> as the template argument to make_unique is cumbersome. Granted, it is easy enough to create a wrapper function that does the type deduction for you:
> >
> > template <typename T>
> > auto as_unique_ptr(T&& t) { return std::make_unique<T>(std::forward<T>(t)); }
> >
> > auto foo_ptr = as_unique_ptr(external_library::make_foo());
> >
> > or something similar.
>
> Perhaps something like:
>
> auto foo_ptr = std::unique_ptr(external_library::make_foo());
>
> This works just fine in C++17 through class template argument deduction.

Well, first of all, that's not the same thing, because make_unique
constructs a unique_ptr<T> from a T,
and unique_ptr<T> could constructor from a T*, but not from a T.
Second, that doesn't work because unique_ptr doesn't have the
deduction guides that would be necessary
to make that deduction-from-pointer work.

Received on 2020-07-07 15:55:18