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编译示例
待解答疑问
- 为什么GCC会允许上述未定义符号的使用,正常完成编译?
- 已知
SUSMA<SCM>明确公有继承自AB,为什么Clang会提示无法将其传入AB const&类型的函数参数?
内容的提问来源于stack exchange,提问作者Bulletmagnet
相关产品推荐
相关产品推荐

