C++ 为什么不能在 constexpr 函数中调用字符串大小函数
C++ Why can't the string size funtion be called within constexpr function
constexpr bool isShorter(const string &s1, const string &s2)
{
return s1.size() < s2.size();
}
编译时说:"error call to non-constexpr function"
您不能从 constexpr
函数内部调用非 constexpr
函数。而且,从 here 可以看出,std::string::size()
不是 constexpr
。
std::string::size()
不是 constexpr
使用文字 C 字符串,您可以这样做:
template <std::size_t N1, std::size_t N2>
constexpr bool isShorter(const char (&)[N1], const char (&)[N2])
{
return N1 < Ns;
}
constexpr bool isShorter(const string &s1, const string &s2)
{
return s1.size() < s2.size();
}
编译时说:"error call to non-constexpr function"
您不能从 constexpr
函数内部调用非 constexpr
函数。而且,从 here 可以看出,std::string::size()
不是 constexpr
。
std::string::size()
不是 constexpr
使用文字 C 字符串,您可以这样做:
template <std::size_t N1, std::size_t N2>
constexpr bool isShorter(const char (&)[N1], const char (&)[N2])
{
return N1 < Ns;
}