Tim*_*mmm 6 c++ initializer-list c++11
我该如何工作:
void foo(uint8_t a[]) { ... }
foo({0x01, 0x02, 0x03});
Run Code Online (Sandbox Code Playgroud)
它给了我一个错误:
error: cannot convert '<brace-enclosed initializer list>' to 'uint8_t* {aka unsigned char*}' for argument '1'
^
Run Code Online (Sandbox Code Playgroud)
这对我有用,我不得不改变函数签名,但实际上它在我的情况下更好,因为它静态检查数组长度:
void foo(std::array<uint8_t, 3> 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.
Run Code Online (Sandbox Code Playgroud)
到目前为止,答案还没有解决问题的主要问题:在签名中
void foo(uint8_t a[])
Run Code Online (Sandbox Code Playgroud)
a不是数组,而是指向 a 的指针uint8_t。尽管事实上声明a使它看起来像一个数组。错误消息甚至指出了这一点:
cannot convert '<brace-enclosed initializer list>' to 'uint8_t* {aka unsigned char*}'
Run Code Online (Sandbox Code Playgroud)
因此,以同样的方式,您不得这样做:
uint8_t *a = {0x01, 0x02, 0x03}; // Eek! Error
Run Code Online (Sandbox Code Playgroud)
你不能foo({0x01, 0x02, 0x03});用上面的签名打电话。
我建议您花一些时间阅读 C 风格的数组以及它们如何不是C++ 中的一等公民。
从您发布到您自己的问题的答案来看,您似乎正在寻找一个适用于固定大小数组的函数。但是不要按值传递它!我建议使用以下声明:
void foo(std::array<uint8_t, 3> const &a);
Run Code Online (Sandbox Code Playgroud)