我想知道当我传递 integer
时 clang 编译器的以下警告到std::initializer_list< 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 >
,即
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]:
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.
我们正在从 int
(允许负值)转换为 size_t
(不允许),因此这是一个收缩转换。缩小转换在列表初始化中格式错误,这就是您在这里所做的:
std::initializer_list<size_t> i_l = { i };
但是,在其他地方(就标准而言)缩小转换很好:
s_t = i;
这就是为什么第一行格式错误而第二行不是。
关于c++ - 将 int 转换为 size_t,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41248340/