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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 00:05:58