gpt4 book ai didi

c++ - 是否可以避免初始化列表中的 static_cast ?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:20:43 25 4
gpt4 key购买 nike

在我的代码库中,我经常使用以下语法初始化数组或 vector if bytes:

uint16_t foo = 0xAB, bar = 0xCD

// bytes = { 0xA, 0xB, 0xC, 0xD }
std::array<uint8_t, 4> bytes = {{
foo >> 8,
foo & 0x00FF,
bar >> 8,
bar & 0x00FF
}};

我从 clang++ 得到以下错误:

error: non-constant-expression cannot
be narrowed from type 'int' to 'value_type' (aka 'unsigned char') in initializer list [-Wc++11-narrowing]
foo >> 8,
^~~~~~~~~~~~~

编译器建议我添加一个 static_cast 来消除错误。我知道强制转换会起作用,但我想知道是否有可能避免强制转换并保持现有的语法优雅?

感谢您的帮助。

最佳答案

您可以这样做,而不是多次添加 static_cast:

template <class ... Ts>
std::array<uint8_t, sizeof...(Ts)> make_char_array(Ts && ... ts) {
return {{static_cast<uint8_t>(ts)...}};
}

然后使用与之前相同的参数执行 auto bytes = make_char_array(...)

关于c++ - 是否可以避免初始化列表中的 static_cast ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46545847/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com