Adding const keyword to an array passed as a parameter to function

前端 未结 5 1026
死守一世寂寞
死守一世寂寞 2021-02-07 07:17

Is there any way that I can add const keyword to an array passed as a parameter to function:

void foo(char arr_arg[])

If I place <

5条回答
  •  长情又很酷
    2021-02-07 07:51

    There's several ways in C++, but none are quite what you seem to be expecting.

    //typedef has a very clear intent
    typedef char* array;
    void f0(const array a) {}
    
    //switch to pointers to sidestep the problem
    void f1(char* const a) {}
    
    //references are inherently const
    //can't take pointers, but guarantees the size, sometimes nice
    //this version obviously doesn't work in C
    template
    void f2(char (&a)[n]) {}
    

    http://ideone.com/4LvYT

提交回复
热议问题