Initialiser list passed as function parameter for array

后端 未结 5 1383
醉梦人生
醉梦人生 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条回答
  •  梦毁少年i
    2020-12-19 08:08

    This:

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

    is a function that takes a uint8_t*, not an array - arrays are decayed to pointers when used as function arguments. The issue is that an initializer list (like {0x01, 0x02, 0x03}) cannot be converted to a uint8_t*.

    If what you want is to pass an arbitrary number of uint8_ts to foo, the simple solution is to use the new std::initializer_list

    void foo(std::initializer_list a) { ... }
    
    foo({0x01, 0x02, 0x03, 0x04, 0x05}); // OK - a has 5 elems in it
    

    Or you could take a variadic pack and construct an array from it internally:

    template ::value...>
                  >>
    void foo(Args... elems) {
        uint8_t a[] = {elems...};
        // ...
    }
    

    That has slightly different usage:

    foo({0x01, 0x02, 0x03}); // error
    foo(0x01, 0x02, 0x03; // OK - a has 3 elems in it
    

提交回复
热议问题