Initialiser list passed as function parameter for array

后端 未结 5 1389
醉梦人生
醉梦人生 2020-12-19 07:49

How do I make this work:

void foo(uint8_t a[]) { ... }

foo({0x01, 0x02, 0x03});

It gives me an error:

error: cannot conver         


        
5条回答
  •  無奈伤痛
    2020-12-19 08:34

    This worked for me, I had to change the function signature but it's actually better in my case as it statically checks the array length:

    void foo(std::array a) { /* use a.data() instead of a */ }
    
    foo({0x01, 0x02, 0x03}); // OK
    
    foo({0x01, 0x02}); // Works, at least on GCC 4.9.1. The third value is set to zero.
    
    foo({0x01, 0x02, 0x03, 0x04}); // Compilation error.
    

提交回复
热议问题