为何Clang中std::string的constexpr比较无法通过编译?
问题:constexpr if中std::string比较在Clang编译失败的原因
我想编写一个模板函数,根据模板参数所属的类调用其对应方法。我清楚使用std::is_same是实现该需求的更优方式,但这与本次问题无关。以下是最简示例代码:
#include <iostream> #include <string> class A { public: static constexpr std::string name() {return "a";} void onlyInA() const {std::cout << "only in a\n";} }; class B { public: static constexpr std::string name() {return "b";} }; template <typename C> void func() { C c_{}; if constexpr (C::name() == "a") { c_.onlyInA(); } } int main() { func<A>(); func<B>(); }
两个类均拥有返回std::string的static constexpr方法,模板函数中通过constexpr比较该字符串,以决定是否调用特定方法。该代码在GCC中可正常编译,但在Clang中无法编译。Clang给出的错误信息为:
constexpr if condition is not a constant expression
我已找到两种在Clang中修复该问题的方法:
- 将
name方法的返回类型改为std::string_view - 将
C::name()存入static constexpr变量后再进行比较
但我仍不理解为何原版本代码在Clang中无法运行,根据cppreference的说明,std::string的比较运算符是constexpr的。
内容的提问来源于stack exchange,提问作者Ivan Gorin
相关产品推荐
相关产品推荐

