c++ - 将 int 转换为 size_t

标签 c++ casting initializer-list

我想知道当我传递 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/

相关文章:

c++ - 程序执行步骤

python - 在 python 中使用非标准类型进行类型转换

c++ - initializer_list 和模板类型推导

c++ - 为什么我的初始化列表对于类型推导是半忽略的?

c++ - 在 C++ 中,如何从声明中获取任意函数的类型?

c++ - 程序执行期间的 sigsegv

c++ - 在 C++ 中实现二维区间搜索的最佳方法是什么?

c# - 将 ComponentRegistration 向下转换为非泛型类型

int16_t 到 int 的对话是否会导致实现定义的行为?

c++ - std::initializer_list 作为函数参数