Runtime Arrays and Pointer Decay

I tested some of the tools in the type_traits header on new C ++ 14 runtime arrays, consider the code below:

 int g[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}; template <typename T> void print(T &t) { std::cout << "Type id: " << typeid(T).name() << '\n'; std::cout << "is_array: " << std::is_array<decltype(T)>::value << '\n'; std::cout << "is_pointer: " << std::is_pointer<decltype(T)>::value << '\n'; std::cout << "extent: " << std::extent<decltype(T)>::value << '\n'; } int main() { print(g); return 0; } 

An array of static size g returns the following result:

 Type id: A11_i is_array: 1 is_pointer: 0 extent: 11 

The A11_i name is A11_i I assume that it is A rray of 11 elements of type int , so everything is correct here, but with this new code:

 void f(std::size_t s) { int a[s]; print(a); } int main() { f(5); return 0; } 

I get errors:

 In function 'void f(std::size_t)': error: no matching function for call to 'print(int [s])' note: candidate is: note: template<class T> void print(T&) note: template argument deduction/substitution failed: note: variable-sized array type 'int [s]' is not a valid template argument 

I did not expect that the size argument could be passed to the template, but I expected the matrix to automatically break into a pointer. I think the T & argument is not suitable for this kind of decay, so I tried changing the template signature to:

 template <typename T> void print(T *&t) 

With similar results:

 In function 'void f(std::size_t)': error: no matching function for call to 'print(int [s])' note: candidate is: note: template<class T> void print(T*&) note: template argument deduction/substitution failed: note: mismatched types 'T*' and 'int [s]' 

And I noticed that the size variable in the runtime size array is tied to the type (instead of mismatched types 'T*' and 'int [ 5 ]' we get mismatched types 'T*' and 'int [ s ]' ), it looks pretty weird.

So what is the question?

  • Why am I not getting decomposition from array to pointer in this array of runtime size?
  • Is a variable used to determine the size of an array of runtime size type array of runtime size or am I misunderstanding an error?
+7
c ++ arrays c ++ 14 variable-length-array
source share
1 answer

When a template argument is output, the conversion of an array to a pointer is used only if the parameter type of the function template is not a reference.

ยง14.8.2.1 Derivation of template arguments from function call [Temp.deduct.call]

1 The output of the template argument is made by comparing each function with the type of the template parameter (name it P ) with the type of the corresponding call argument (name it A ), as described below. [...]

2 If P not a reference type:

  • If A is an array type, instead of A , the pointer type created by the standard transformation (4.2) from the matrix to the pointer is used to subtract the type; otherwise,
  • [...]
+3
source share

All Articles