I can write a templated function this way
template<class T> void f(T x) {…}
or this way
template<class T> void f(T const& x) {…}
I guess that the second option can be more optimal as it explicitly avoids a copy, but I suspect that it can also fail for some specific types T
(eg functors?).
So, when should use the first option, and when to use the second? There are also this boost::call_traits<T>::param_type
and boost::reference_wrapper
that were in the answers to my previous question, but people don't use them everywhere, do they? Is there a rule of thumb for this? Thanks.
Is there a rule of thumb for this?
The same general rules for when to use pass by reference vs. pass by value apply.
If you expect T
always to be a numeric type or a type that is very cheap to copy, then you can take the argument by value. If you are going to make a copy of the argument into a local variable in the function anyway, then you should take it by value to help the compiler elide copies that don't really need to be made.
Otherwise, take the argument by reference. In the case of types that are cheap to copy, it may be more expensive but for other types it will be faster. If you find this is a performance hotspot, you can overload the function for different types of arguments and do the right thing for each of them.