jeudi 3 mai 2018

Forward individual members of a Forward reference

I have a function that potentially moves a generic argument but through their members. What of these options is more correct:

  1. This seems the more natural but it is strange because the argument is potentially moved twice, which is odd because the object can become invalid.

    template<class T> 
    void fun(T&& t){
        myhead_ = std::forward<T>(t).head_;
        myrest_ = std::forward<T>(t).rest_;
    }
    
    
  2. This can't be incorrect but it may not be moving anything.

    template<class T> void fun(T&& t){
        myhead_ = std::forward<decltype(t.head_)>(t.head_);
        myrest_ = std::forward<decltype(t.rest_)>(t.rest_);
    }
    
    
  3. This seems correct but too much code.

    template<class T> void fun(T& t){
        myhead_ = t.head_;
        myrest_ = t.rest_;
    }
    template<class T> void fun(T&& t){
        myhead_ = std::move(t.head_);
        myrest_ = std::move(t.rest_);
    }
    
    

Aucun commentaire:

Enregistrer un commentaire