本文介绍了将int转换为size_t的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 当我将整数传递给 std :: initializer_list<时,我想知道以下有关clang编译器的警告。 size_t> :non-constant-expression cannot be narrowed from type 'int' to 'unsigned long' in initializer list为什么 int 强制转换为 size_t ,但 int 不会传递给 std :: initializer_list< ; size_t> ,即Why can int be casted to a size_tbut an int not be passed to an std::initializer_list< size_t >, i.e.int main(){ size_t s_t = 0; int i = 0; std::initializer_list<size_t> i_l = { i }; // warning s_t = i; // no warning return 0;}推荐答案您违反了 [dcl.init.list] / 7 缩小转换是从整数类型或无范围枚举类型到不能表示原始值的整数类型的隐式转换[...]类型,除非源是一个常数表达式,其整数提升后的值将适合目标类型。 A narrowing conversion is an implicit conversion[...] from an integer type or unscoped enumeration type to an integer type that cannot represent all the values of the original type, except where the source is a constant expression whose value after integral promotions will fit into the target type.自 i 不是一个常量表达式,它被视为缩小转换,并且初始化器列表中不允许缩小转换。如果要使用Since i is not a constant expression this counts as a narrowing conversion and narrowing conversions are not allowed in initializer list. If you were to usestd::initializer_list<std::size_t> i_l = { 0 };然后即使 0 也不会缩小是 int ,因为编译器知道 0 可以用每种类型表示。Then it would not narrow even though 0 is an int since the compiler knows 0 can be represented in each type. 这篇关于将int转换为size_t的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-19 15:07