简体   繁体   中英

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!

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)...);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM