获取模板参数对象的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
相关产品推荐
相关产品推荐

