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

前端 未结 5 891
抹茶落季
抹茶落季 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:22

    Because arrays can not be passed by value as a function parameter.
    When you pass them by value they decay into a pointer.

    In this function:

    template 
    void f(T buff) {
    

    T can not be char (&buff)[3] as this is a reference. The compiler would have tried char (buff)[3] to pass by value but that is not allowed. So to make it work arrays decay to pointers.

    Your second function works because here the array is passed by reference:

    template 
    void f1(T& buff) {
    
    // Here T& => char (&buff)[3]
    

提交回复
热议问题