c++ - std::forward 不允许接受左值
问题描述
下面是insert()
一个最大堆的成员函数的实现。我尝试使用std::forward
它,因为我认为它可以替代编写接受左值的此函数的重载。但是,该代码仍然不适用于左值。任何想法为什么?
注意:是类中values
的私有。vector<T>
max_heap
template <typename T, typename compare_type>
void max_heap<T, compare_type>::insert(T&& item){
if(values.empty()){
values.push_back(std::forward<T>(item));
return;
}
values.push_back(std::forward<T>(item));
size_t child_pos = values.size()-1;
size_t parent_pos = (child_pos-1)/2;
//stop swapping either when inserted child at root or smaller than parent
while(child_pos != 0 && pred(values[parent_pos], values[child_pos])){
std::swap(values[parent_pos], values[child_pos]);
child_pos = parent_pos;
parent_pos = (child_pos-1)/2;
}
}
解决方案
要创建转发引用,您的参数类型必须作为同一函数模板的模板参数存在。(有关更多信息,请参阅前向引用的(1)。)
在您的情况下,模板参数T
来自类max_heap
而不是函数的模板参数列表,因此item
用作右值引用(不能绑定到左值)而不是转发引用。
对于您的情况,请尝试以下操作:
#include <cstddef>
#include <utility>
#include <vector>
// Other header includes go here ...
template <typename T, typename compare_type>
class max_heap {
// Other instance variables go here ...
public:
template <typename U> // <- Notice how the template parameter 'U' is bound to the 'same function template'
void insert(U&& item);
// Other member methods go here ...
};
// ...
template <typename T, typename compare_type>
template <typename U>
void max_heap<T, compare_type>::insert(U&& item){
if(values.empty()){
values.push_back(std::forward<U>(item));
return;
}
values.push_back(std::forward<U>(item));
size_t child_pos = values.size()-1;
size_t parent_pos = (child_pos-1)/2;
//stop swapping either when inserted child at root or smaller than parent
while(child_pos != 0 && pred(values[parent_pos], values[child_pos])){
std::swap(values[parent_pos], values[child_pos]);
child_pos = parent_pos;
parent_pos = (child_pos-1)/2;
}
}
// Other definitions go here ...
推荐阅读
- android - PagedListAdapter 将 newItem 作为 oldItem 传递给 DiffUtil.ItemCallback
- azure - Azure 中的 Kafka 集群创建卡在验证中
- python - 如何找到不同大小列表的中位数
- excel - 循环浏览一些文件(打开、添加列、保存和关闭)
- javascript - Highstock / Highcharts - 在其下方标记线条颜色遮蔽线
- javascript - 如何从参数数组形成单个字符串?
- sublimetext3 - 崇高着色括号之间的所有内容与外部颜色不同
- reactjs - 使用 gitlab-ci 部署 React 应用程序的最佳方式?
- javascript - 使用正则表达式创建字典以将值分配给键的最有效方法是什么?
- angularjs - 全局变量作为angularjs中的服务