Understanding type inference for universal references

Let be fooa function:

template< typename T >
void foo( T&& a ){}

What type will be displayed Tfor the following calls foo:

foo( 0 ); // is T here int or int&& ?

int a = 0;
foo( a ); // is T here int or int& ?
+4
source share
3 answers

The standard rule for type inference is that reference types can never be the result of deduction. Given this code,

template <class T>
void bar(T par);

bar(0);
int a;
bar(a);
int &b;
bar(b);

all 3 calls will call foo<int>. That is, it is Tdisplayed on int, but parhas a type int.

: , (.. T&& T), l X, X & X .

, , X X X & ; X && .

( , , ):

template <class T>
void foo(T &&par);

foo(0);

int a;
foo(a);

foo(0) rvalue int. int , , T int ( foo<int>), par - int &&.

foo(a) l int. Forwarding int & . T int & ( foo<int&>), par - "int & &&", int &.

+5

foo (0);// T int int &&

An int.

int a = 0; foo (a);// T int int &

An int&.

+1

T&& , ,

template< typename T >
void foo( T&& a ){}

.. T , .

,

  • lvalue type, T&& type& &&, type&

  • if the provided argument is an rvalue of type type, it T&& will expand to type &&that collapses totype&&

Please note that both link parameters , if you need to call the rvalue value overloading another function, you need to dostd::forward<T>(a)

+1
source

Source: https://habr.com/ru/post/1686857/


All Articles