why does the array decay to a pointer in a template function

前端 未结 5 913
抹茶落季
抹茶落季 2020-12-16 04:24

I don\'t understand why the array decays to a pointer in a template function.

If you look at the following code: When the parameter is forced to be a reference (fun

5条回答
  •  情话喂你
    2020-12-16 05:16

    The reason basically boils down to type deduction when matching the different overloads. When you call f the compiler deduces the type to be const char[3] which then decays into const char* because that's what arrays do. This is done in the same exact way that in f(1) the compiler deduces T to be int and not int&.

    In the case of f1 because the argument is taken by reference, then the compiler again deduces T to be const char[3], but it takes a reference to it.

    Nothing really surprising, but rather consistent if it were not for the decay of arrays to pointers when used as function arguments...

提交回复
热议问题