如何创建 emplace_back 方法? [英] How to create an emplace_back method?

查看:42
本文介绍了如何创建 emplace_back 方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个自定义的 ArrayList/Vector 类,但在创建 emplace_back 函数时遇到了麻烦.如何创建与 ArrayList 的value_type 类"的构造函数相同的参数?

解决方案

emplace_back 和类似的函数(std::make_shared 等)不需要知道什么关于他们试图构建的 value_type.这要归功于 C++11 中引入的参数包.>

使用参数包,您可以创建一个接受任意数量参数(任意类型)的函数.
假设您已经实现了 push_backemplace_back 可能如下所示:

templatevoid emplace_back(Args&&... args){push_back(value_type(args...));}

但是有一个问题.传递参数可以改变它们的类型(特别是当我们处理移动语义时:当传递给另一个函数时,右值引用将变成左值引用).这可能是不可取的 - 当 l-value 或 r-value 传递时,用户可能会重载方法来做不同的事情.
这就是使用 std::forward 完美转发的地方进来了.使用 std::forward,我们可以进一步传递参数,就像它们传递到您的函数中一样.

templatevoid emplace_back(Args&&... args){push_back(value_type(std::forward(args)...));}

查看我的(非常糟糕的)示例:https://wandbox.org/permlink/KyQJU8rd2FGTTFLJ

I´m creating a custom ArrayList/Vector class and I´m having troubles creating an emplace_back function. How can I create arguments that are the same as the constructor of the "value_type class" of the ArrayList ?

解决方案

emplace_back and similar functions (std::make_shared etc.) don't need to know anything about value_type they are trying to contruct. This is possible thanks to parameter packs introduced in C++11.

Using parameter pack, you can make a function that takes any number of arguments (with any types).
Assuming that you have push_back implemented, emplace_back may look like this:

template<class... Args>
void emplace_back(Args&&... args)
{
    push_back(value_type(args...));
}

There is a catch however. Passing arguments around can change their type (especially when we're dealing with move semantics: r-value reference will become l-value reference when passed to another function). This may be undesireable - user may overload methods to do different things when l-value or r-value passed.
That's where perfect forwarding with std::forward comes in. Using std::forward, we may pass the arguments further exactly like they were passed into your function.

template<class... Args>
void emplace_back(Args&&... args)
{
    push_back(value_type(std::forward<Args>(args)...));
}

See my (very bad) example of it working: https://wandbox.org/permlink/KyQJU8rd2FGTTFLJ

这篇关于如何创建 emplace_back 方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆