How to call void foo (int (&) []) {} in C ++?

void f1(int (&)[8]) {} void f2(int (&)[]) {} int main() { int a[8]; f1(a); // OK f2(/* What should I put here? */); // ??? return 0; } 

How do I call f2?

PS: void f2 (int (&) []) {} is legal according to VC ++ 2012.

consider the following:

 template<class T> struct A {}; template<class T> struct A<T[]> {}; template<class T, size_t size> struct A<T[size]> {}; 
+4
source share
2 answers

C ++ has an explicit rule that prohibits references or pointers to arrays without borders as parameters (but these are otherwise valid types). The following will be a valid argument for such a parameter.

 extern int arg[]; 

Please note: you cannot use an array with size. In C ++, there is no concept of type compatibility. C has and creates an array type without size compatible with the corresponding array type with size. In C ++, the type system is more stringent, types have relationships and prototype function types do not exist, so type compatibility is not a real need, so C ++ abandoned it.

+5
source

"f2" should not be compiled in the first place. You can only omit the size of the array parameter if [] is the first level of indirection, so to speak, in this case it is actually not an array, but a pointer. In this case, the first level of indirection is &, so you cannot omit the size in [].

+5
source

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


All Articles