MSVC与GCC/Clang的constexpr构造器编译差异(已由微软修复)
为什么这段带constexpr构造器的代码在MSVC C++20下编译失败,但GCC/Clang正常?
这是MSVC的编译器回归问题,目前微软已经修复。
你的代码逻辑本身符合C++20标准:
- 嵌套结构体
SupportedParam通过constexpr构造器接收成员函数指针并初始化成员变量 - 在
SupportedParameters函数中,构建了constexpr std::array存储SupportedParam实例,并用static_assert验证成员函数指针的一致性 - GCC和Clang能正确识别并处理这种constexpr上下文中的成员函数指针初始化逻辑,但旧版本MSVC存在编译缺陷,无法正确解析该场景
代码示例:
#include <iostream> #include <array> class TestX { bool GetA(char* outVal, unsigned int outValLen) {(void)outVal, (void)outValLen; return false;} struct SupportedParam { using GetParamFunc = bool (TestX::*)(char* outVal, unsigned int outValLen); constexpr SupportedParam(GetParamFunc gp) : GetParam(gp) {} GetParamFunc GetParam; }; static const auto& SupportedParameters() { static constexpr std::array<SupportedParam,1> t = { SupportedParam(&TestX::GetA) }; static_assert(t[0].GetParam == &TestX::GetA); return t; }; public: void Print() { for(auto& x : SupportedParameters()) { std::cout << (this->*x.GetParam)(nullptr, 0); } } }; int main(void) { TestX x; x.Print(); }
内容的提问来源于stack exchange,提问作者Ashley Duncan
相关产品推荐
相关产品推荐

