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

C++中能否将匿名union声明为constexpr?

C++中constexpr匿名union的编译行为差异

我承认下面的问题可能不太实用,但能找到答案仍是不错的。

在C++的全局作用域中,我们可以声明一个带constexpr的匿名union,同时定义对应的变量,这种写法在所有主流编译器中都能正常通过:

constexpr static union {
    int i = 1;
} u; // 所有编译器均支持

仅带static的匿名union同样是合法写法,也能被所有编译器接受:

static union {
    int j = 1;
}; // 所有编译器均支持

但如果尝试直接把匿名union声明为constexpr,情况就不一样了:

constexpr static union {
    int k = 1;
}; // 仅GCC支持

不同编译器的报错表现存在明显差异:

  • GCC:可以正常编译通过
  • MSVC:输出错误提示:error C2737: 'k': constexpr object must be initialized(注:代码中已经对k做了初始化,该报错逻辑存在矛盾)
  • Clang:输出错误提示:union cannot be marked constexpr

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 22:07:06