C++ Logo

std-discussion

Advanced search

Re: std::make_shared and type deduction

From: Jason McKesson <jmckesson_at_[hidden]>
Date: Tue, 7 Jul 2020 16:45:46 -0400
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.

Received on 2020-07-07 15:49:12