What's the difference between
template <class T,class ARG_T=T&>
and
template <class T,class ARG_T=T>
What's the difference between
template <class T,class ARG_T=T&>
and
template <class T,class ARG_T=T>
It's a good way of eliminating taking unnecessary value copies in functions based on that template, but in an optional way The &
denotes a reference type.
E.g. you could have the function
template <class T, class ARG_T = T&>
T add(std::type_identity_t<ARG_T> v1, std::type_identity_t<ARG_T> v2){
return v1 + v2;
}
The use of type_identity
prevents an unwanted deduction to the T
type (see Template default argument loses its reference type).
This means that a value copy of v1
and v2
are not taken. Of course, it's not always more efficient to take references, so for some instantiations, you might want ARG_T
to be the same as T
.
Template type arguments are (dependent) type names. The ampersand after a type name makes it an lvalue reference. If T
is already reference, then reference collapsing rules apply.