错误:“std::array<std::counting_semaphore<1>, 4>”的初始值设定项过多 [重复]

error: too many initializers for ‘std::array<std::counting_semaphore<1>, 4>’ [duplicate]

提问人:digito_evo 提问时间:4/22/2023 最后编辑:Vlad from Moscowdigito_evo 更新时间:4/23/2023 访问量:107

问:

以下代码片段无法编译。我尝试了不同的初始值设定项,但无法使其编译。

#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} };
      |                                                                          ^

不能声明一个 s 数组吗?正确的语法是什么?binary_semaphore

C++ C++20 初始值设定项列表 stdarray 二进制信号量

评论


答:

6赞 Vlad from Moscow 4/22/2023 #1

一般来说,你可以写,例如,再添加一对大括号,比如

std::array<std::binary_semaphore, 4> semaphores { { {0}, {0}, {0}, {0} } };

否则,第一个初始值设定项将被视为 std::array 类型的整个对象的初始值设定项。{0}

但是,还有另一个问题。构造函数是显式的。

constexpr explicit counting_semaphore(ptrdiff_t desired);

因此,您需要在初始值设定项中使用显式构造函数。

例如

    std::array<std::binary_semaphore, 4> semaphores 
    { 
        { 
            std::binary_semaphore{ 0 }, 
            std::binary_semaphore{ 0 }, 
            std::binary_semaphore{ 0 }, 
            std::binary_semaphore{ 0 } 
        }
    };

在这种情况下,您也可以在不引入其他大括号的情况下进行写作,例如

    std::array<std::binary_semaphore, 4> semaphores 
    { 
            std::binary_semaphore{ 0 }, 
            std::binary_semaphore{ 0 }, 
            std::binary_semaphore{ 0 }, 
            std::binary_semaphore{ 0 } 
    };
1赞 digito_evo 4/22/2023 #2

问题似乎与 的构造函数有关。explicitstd::binary_semaphore

以下代码编译:

#include <array>
#include <semaphore>


int main()
{
    std::array<std::binary_semaphore, 4> semaphores { std::binary_semaphore { 0 }, std::binary_semaphore { 0 },
                                                      std::binary_semaphore { 0 }, std::binary_semaphore { 0 } };
    auto& [ lock1, lock2, lock3, lock4 ] { semaphores };
}

不过它看起来并不整洁。

评论

3赞 ildjarn 4/22/2023
您可以通过使用 CTAD 来降低噪音,即 而不是 .std::array semaphoresstd::array<std::binary_semaphore, 4> semaphores
0赞 digito_evo 4/22/2023
@ildjarn 哦,太好了。在这种情况下,这是一个不错的选择。我没有想到。