When should I use forward and move?

后端 未结 4 1875
长情又很酷
长情又很酷 2021-02-05 12:07

I have a code that operates on a vector:

template
void doVector(vector& v, T&& value) {
    //....
    v.push_back(value);         


        
4条回答
  •  天涯浪人
    2021-02-05 12:43

    The current code will not compile when the second argument is lvalue because T&& will turn out to be X& which means T needs to be X& which in turn means std::vector will become std::vector which will NOT match the first argument which is std::vector &. Hence, it is an error.

    I would use two template parameters:

    template
    void doVector(vector & v, V && value) 
    {
        v.emplace_back(std::forward(value));
    }
    

    Since V could a different type from T, so emplace_back makes more sense, because not only it solves the problem, it makes the code more generic. :-)

    Now the next improvement : since we're using emplace_back which creates the object of type T from argument value (possibly using constructor), we could take advantage of this fact, and make it variadic function:

    template
    void doVector(vector & v, V && ... value) 
    {
        v.emplace_back(std::forward(value)...);
    }
    

    That is even more generic, as you could use it as:

    struct point
    {
        point(int, int) {}
    };
    
    std::vector pts;
    doVector(pts, 1, 2);
    
    std::vector ints;
    doVector(ints, 10);
    

    Hope that helps.

提交回复
热议问题