简体   繁体   English

如何为`std::make_unique 创建一个包装器<t> `?</t>

[英]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.我想为std::unique_ptr<T>std::make_unique<T>创建一个包装器,因为我认为它们看起来很难看并且需要很长时间才能输入。 (Yes, I'm that kind of person). (是的,我就是这样的人)。

I have completed my UniquePtr type alias with no problem but cannot get my MakeUnique to work.我已经毫无问题地完成了我的UniquePtr类型别名,但无法让我的MakeUnique工作。 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.然后,您需要转发,因为args...会复制所有内容。 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)...);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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