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

获取模板参数对象的constinit引用时编译器行为不一致,是否为MSVC Bug?

MSVC编译非类型模板参数静态值代码的兼容性问题

此前有技术讨论探讨过基于非类型模板参数创建静态值的实现方案,但对应的代码在MSVC编译器下无法通过编译,而GCC与Clang可正常处理。

最小复现代码

#include <type_traits>

template <class T>
struct value_holder {
    T value;
};

template <auto V>
constexpr auto const& make_static() {
    if constexpr (std::is_class_v<decltype(V)>) {
        return V;
    } else {
        return make_static<value_holder{V}>().value;
    }
}

int main() {
    [[maybe_unused]] constinit static const auto v = make_static<2>();
    [[maybe_unused]] constinit static const auto& r = make_static<2>();

    return v;
}

编译结果对比

  • GCC、Clang:可正常编译通过
  • MSVC 19.40版本:输出编译错误

error C2127: 'r': illegal initialization of 'constinit' entity with a non-constant expression

结论

这属于MSVC的编译器Bug。根据C++标准,make_static<2>()的返回值是常量表达式,完全符合constinit的初始化要求,MSVC的错误判定不符合标准规范。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 21:13:12