-1

What's the difference between

template <class T,class ARG_T=T&>    

and

template <class T,class ARG_T=T>    
  • 5
    It's a reference. Possible duplicate of [What are the differences between a pointer variable and a reference variable in C++?](https://stackoverflow.com/questions/57483/what-are-the-differences-between-a-pointer-variable-and-a-reference-variable-in) – L. F. Sep 06 '19 at 09:54
  • This has me stumped on the default argument treatment. See my question https://stackoverflow.com/questions/57820195/template-default-argument-loses-its-reference-type – Bathsheba Sep 06 '19 at 10:28

2 Answers2

3

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.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • but when I use your code as add(a,b) , the translater(vs2019 community) just analyze this into "int add(int v1, int v2)" rather than "int add(int &v1, int &v2)" – mioyuki2009 Sep 06 '19 at 10:03
  • 1
    @mioyuki2009: Actually I get the same as you if I don't include the `int&` explicitly. I don't know why. I've asked the question here; https://stackoverflow.com/questions/57820195/template-default-argument-loses-its-reference-type – Bathsheba Sep 06 '19 at 10:22
0

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.

eerorika
  • 232,697
  • 12
  • 197
  • 326