如何初始化std::array<std::byte>?编译错误原因与修复方案
编译错误原因
std::byte的构造函数是**显式(explicit)**的(C++17标准规定),禁止从int类型进行隐式转换:
- 单独初始化
std::byte b {42};属于直接列表初始化,这种模式允许调用显式构造函数,因此编译通过。 - 而
std::array<std::byte, 2> msg {42, 43};是对聚合类型std::array的聚合初始化,此时每个元素的初始化遵循复制初始化规则,编译器会尝试将int隐式转换为std::byte,但显式构造函数拒绝这种隐式操作,因此触发错误。
修复方法
以下几种方案都可以解决问题:
方案1:显式构造每个std::byte元素
在初始化列表中直接构造std::byte对象:
#include <cstddef> #include <array> int main() { std::byte b {42}; // OK std::array<std::byte, 2> msg {std::byte{42}, std::byte{43}}; // OK }
方案2:用static_cast显式转换
通过static_cast将int转换为std::byte:
#include <cstddef> #include <array> int main() { std::byte b {42}; // OK std::array<std::byte, 2> msg {static_cast<std::byte>(42), static_cast<std::byte>(43)}; // OK }
方案3:C++20字面量(可选)
如果编译器支持C++20,可以使用std::byte的用户定义字面量,需要引入对应的命名空间:
#include <cstddef> #include <array> using namespace std::literals; int main() { std::byte b {42}; // OK std::array<std::byte, 2> msg {42_b, 43_b}; // OK(C++20) }
内容的提问来源于stack exchange,提问作者DailyLearner
相关产品推荐
相关产品推荐

