为何Clang中constexpr函数可调用非constexpr的std::format?
为什么Clang允许constexpr函数调用非constexpr的std::format?
这本质是Clang对C++标准的扩展实现,以及标准库函数与自定义函数的区别导致的:
Clang对std::format的超前支持:C++23才正式将
std::format标记为constexpr,但Clang在更早版本中,就把自家标准库的std::format实现成了符合常量表达式要求的逻辑。即使函数没有constexpr说明符,只要编译器确认其内部行为能在常量求值上下文运行,就允许在constexpr函数里调用它——这是Clang的扩展性实现。自定义函数无特殊豁免:你写的
myformat是普通非constexpr函数,编译器会严格按照C++标准检查:非constexpr函数不能在constexpr函数的常量求值路径中被调用,所以触发编译错误是符合标准的行为。MSVC的严格遵循:MSVC对标准的执行更严格,在C23之前不会将
std::format视为可在constexpr上下文运行的函数,所以不管是调用std::format还是自定义的myformat,都会报C3615错误,这完全符合C20及更早版本的标准规定。
代码示例
// Clang无编译错误,MSVC编译失败 constexpr std::string print() { return std::format("hello"); } std::string myformat() { return "hello"; } // 所有编译器都会报错:non-constexpr function 'myformat' cannot be used in a constant expression constexpr std::string myprint() { return myformat(); }
内容的提问来源于stack exchange,提问作者Ufiso
相关产品推荐
相关产品推荐

