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

C++未使用constexpr值中引用未定义符号的编译器差异问题

GCC与Clang模板编译行为差异问题

以下代码可同时被GCC(12.1)与Clang(14.0)编译通过:

#include <memory>

struct AB{};

struct AM
{
    void ra(std::unique_ptr<AB>  &&) {}
    void rd(AB const&) {}
};

AM amgr;

// 上述成员函数对应的自由函数版本
void fra(std::unique_ptr<AB>  &&) {}
void frd(AB const&) {}

template<typename T>
struct SUSMA : public AB
{
#ifdef SILLY
    constexpr static auto silly = static_cast<int>(T::meow);
#endif
};

template<typename T>
void rscma()
{
    SUSMA<T> sus;
    amgr.rd(sus);

    amgr.ra(std::make_unique<SUSMA<T>>());
}

template<typename T>
void frscma()
{
    SUSMA<T> sus;
    frd(sus);

    fra(std::make_unique<SUSMA<T>>());
}

struct SCM
{
    SCM()
    {
        rscma<SCM>();
        frscma<SCM>();
    }
};

int main()
{
    SCM scm;
}

若定义SILLY宏,两个编译器行为出现分歧:

  • GCC仍可正常编译通过
  • Clang首先会抛出符合预期的错误:SCM中不存在名为meow的成员,同时还会额外抛出两类不符合直觉的错误:
    • 不存在从unique_ptr<SUSMA<SCM>>到unique_ptr<AB>的可行转换
    • 候选函数不可行:frd的第一个参数无法从SUSMA<SCM>转换为const AB

在线复现地址:Godbolt编译示例

待解答疑问

  1. 为什么GCC会允许上述未定义符号的使用,正常完成编译?
  2. 已知SUSMA<SCM>明确公有继承自AB,为什么Clang会提示无法将其传入AB const&类型的函数参数?

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.03 08:21:51