首页 > 解决方案 > 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;
    }
}

标签: c++perfect-forwarding

解决方案


要创建转发引用,您的参数类型必须作为同一函数模板的模板参数存在。(有关更多信息,请参阅前向引用的(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 ...

推荐阅读