samedi 1 août 2015

Forwarding lvalues and rvalues best practice

I have a function that constructs an object from its parameters, defined like so:

template<class T, class ... Args>
void construct(Args && ... args){
    T(std::forward<Args>(args)...);
}

I also have two helper functions that pass into construct.

tempalte<class T, class ... Args>
void add(Args && ... args){
    construct<T>(std::forward<Args>(args)...);
}

tempalte<class T>
void add(T t){
    construct<T>(std::move(t));
}

The first overload of add constructs with parameters, and the second is supposed to take in either an lvalue (in which case it should invoke the copy ctor) or an rvalue (which should invoke the move ctor). My question is, is this the best way to go about doing this? I pass by value for the second overload because I can either copy construct or move construct. I am also wondering if move construction will work correctly if I pass in an rvalue to the second overload, i.e. will the std::forward coupled with the std::move work as I expect it to.

Aucun commentaire:

Enregistrer un commentaire