You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

遍历constexpr std::array时数组索引无警告,运算后触发符号转换警告原因

关于GCC中范围for循环元素作为数组索引的符号转换警告疑问

我认为,由于for循环用于定义运行时控制流,元素声明(如下例中的e)不应被视为常量表达式(尽管它复制了数组x的constexpr元素)。要在索引数组时不触发符号转换警告,必须使用size_t或常量表达式。但为何以下程序编译时无警告(这似乎要求e是常量表达式)?

#include <array>

struct Foo 
{
    enum X
    {
        a,
        b,
        c,
    };

    static constexpr std::array x { a, b, c };
};

int main()
{
    std::array<int, 3> array {};
        
    for (auto e: Foo::x)
        array[e] = 1; 
    
    return 0;
}

然而,将数组赋值行改为(或在[]运算符内进行任何算术运算)会突然触发警告:

array[e * 1] = 1; 
warning: conversion to ‘std::array<int, 3>::size_type’ {aka ‘long unsigned int’} from ‘int’ may change the sign of the result [-Wsign-conversion]
   20 |         array[e * 1] = 1;

使用GCC 13.3.0(禁用扩展和优化)。注:GCC和Clang均使用unsigned int作为枚举X的底层类型,但仅GCC发出警告;MSVC使用int且无警告。

内容的提问来源于stack exchange,提问作者user32744437

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.02 03:12:28