如何正确声明std::array<std::binary_semaphore,4>?编译报错求助
问题
尝试声明std::binary_semaphore数组时编译失败,代码如下:
#include <array> #include <semaphore> int main() { std::array<std::binary_semaphore, 4> semaphores { {0}, {0}, {0}, {0} }; auto& [ lock1, lock2, lock3, lock4 ] { semaphores }; }
报错信息:
SO.cpp:8:74: error: too many initializers for ‘std::array<std::counting_semaphore<1>, 4>’ 8 | std::array<std::binary_semaphore, 4> semaphores { {0}, {0}, {0}, {0} }; | ^
请问是否可以声明binary_semaphore数组?正确的语法是什么?
解决方法
可以声明std::binary_semaphore数组,问题出在初始化的语法嵌套层级错误。
std::array的初始化规则是外层大括号包裹所有元素,你写的{ {0}, {0}, {0}, {0} }给每个元素额外套了一层大括号,导致编译器识别出过多的初始化器。
以下两种都是正确的初始化方式:
方式一:直接初始化元素
去掉每个元素的外层大括号,直接传入初始化值:
std::array<std::binary_semaphore, 4> semaphores { 0, 0, 0, 0 };
方式二:显式嵌套结构
保留std::array的外层包裹大括号,内部直接列出所有元素值:
std::array<std::binary_semaphore, 4> semaphores { {0, 0, 0, 0} };
两种写法都能成功编译,之后的结构化绑定代码可以正常使用。
内容的提问来源于stack exchange,提问作者digito_evo
相关产品推荐
相关产品推荐

