How to create a wrapper for `std::make_unique<T>`?

I'd like to create a wrapper for std::unique_ptr<T> and std::make_unique<T> because I think they look ugly and take too long to type. (Yes, I'm that kind of person).

I have completed my UniquePtr type alias with no problem but cannot get my MakeUnique to work. It seems to be a bit of a rabbit hole, and was wondering if anyone here might be able to give me a hand with this?

What I have so far:

template <class T>
using UniquePtr = std::unique_ptr<T>;

template<typename T, typename... Args>
UniquePtr<T> MakeUnique<T>(Args... args) // recursive variadic function
{
    return std::make_unique<T>(args);
}

Many thanks in advance!


Solution 1:

You need to forward properly the values, and you need to expand the pack.

First, make it compile:

template<typename T, typename... Args>
UniquePtr<T> MakeUnique(Args... args) // not recursive
{ //                   ^---- no need for <T> when defining function template 
    return std::make_unique<T>(args...); // the ... expands the pack
}

Then, you need to forward, because args... will copy everything. You want to move rvalues, and copy lvalues:

template<typename T, typename... Args>
UniquePtr<T> MakeUnique(Args&&... args)
{
    return std::make_unique<T>(std::forward<Args>(args)...);
}