如何创建emplace_back方法?

问题描述 投票:-2回答:1

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

c++ arraylist stdvector push-back emplace
1个回答
0
投票

emplace_back和类似的函数(std::make_shared等)不需要了解他们正在尝试构造的value_type。这要归功于C ++ 11中引入的parameter packs

使用参数包,您可以使函数接受任意数量的参数(具有任何类型)。假设您已实现push_back,则emplace_back可能如下所示:

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

但是有一个陷阱。传递参数可以改变其类型(尤其是当我们处理移动语义时-r值引用将在传递给函数时变为l值引用)。这可能是不希望的-传递l值或r值时,用户可能会重载方法以执行不同的操作。这就是使用std::forward进行完美转发的地方。使用std::forward,我们可以像传递参数一样将参数传递给您。

std::forward

请参阅我的工作非常糟糕的示例:template<class... Args> void emplace_back(Args&&... args) { push_back(value_type(std::forward<Args>(args)...)); }

© www.soinside.com 2019 - 2024. All rights reserved.