Why do const arrays preferably associate parameters with T & constants instead of T && parameters?

It is usually a bad idea to overload a function template with "T & &". parameter, because it can be attached to everything, but let us do it anyway:

template<typename T>
void func(const T& param)
{
  std::cout << "const T&\n";
}

template<typename T>
void func(T&& param)
{
  std::cout << "T&&\n";
}

I realized that overloading const T&would be called for arguments that are lvalues ​​constants, and overloading T&&would be called for all other types of arguments. But think about what happens when we call funcconst and non-const with arrays of content:

int main()
{
  int array[5] = {};
  const int constArray[5] = {};

  func(array);             // calls T&& overload
  func(constArray);        // calls const T& overload
}

VC10, VC11 gcc 4.7 . , const T&. , constArray const, , . T, ( ), " 5 const ints", param const T& " const 5 const ints". constArray const. , func(constArray) T&&, param 5 const ints?

, ++ , , , .

+5
2

( ), cv , . , T = int [5], const T & int const (&) [5].

3.9.3 CV-qualiers [basic.type.quali fier]

2 - [...] cv-, , , (8.3.4).

, func int const [5] :

void func<int [5]>(int const (&) [5])
void func<int const (&) [5]>(int const (& &&) [5])
// where the above collapses to
// 'void func<int const (&) [5]>(int const (&) [5])'

, :

T1 - const T &, T2 - T &&; : T1: = const T & T2: = T &&. (14.5.6.2:3) A1: = const C &, A2: = D && C, D.

T1 T2 (14.8.2.4-2), A1 P2 . (14.8.2.4.5), A1 β†’ const C T2 β†’ T, cv- (14.8.2.4:7), A1 β†’ C T2 β†’ T. T C (14.8.2.4:8), A1 , P2; , A2 β†’ D β†’ D, P1 β†’ const T β†’ T, T D, A2 , P1.

, , ; , P A 14.8.2.4:9, A1 lvalue P2 , T1 , T2. ( cv- .)

+7

rvalue (, int&&) ( , template <typename T> ... T&&).

Rvalue lvalues. . , .

, , int const [5]. :

  • T const &: T = int[5].

  • T &&: T = int const (&)[5].

: . T = int[5] , T = int const (&)[5]. , T = int const (&)[5] T = U const & U = int[5].

, lvalue .

(, array const T &, const. T&&, dedu & shy; cing T = int (&)[5]).

+3

All Articles