Search code examples
c++templatesdecltypetemplate-argument-deduction

Way for class template to deduce type when constructing an instance with std::make_unique?


Let's say we have a class template Foo, that has one type template parameter that it can deduce from an argument in its constructor. If we use std::make_unique to construct an instance of Foo, is there a way for Foo's constructor to deduce the template arguments as it would have if its constructor was called normally? Is this the simplest way to achieve this?

std::make_unique< decltype(Foo{...}) > (...);

This seems pretty clean but if Foo's constructor takes a lot of arguments it can turn into a pretty ugly line.


Solution

  • You can leverage a helper function to wrap the ugly code into a pretty wrapper. That would look like

    template <typename... Args>
    auto make_foo_ptr(Args&&... args)
    {
        return std::make_unique<decltype(Foo{std::forward<Args>(args)...})>(std::forward<Args>(args)...);
    }