C++ C++;为什么可以';不能在constexpr函数中调用字符串大小函数 constexpr bool isShorter(常量字符串&s1,常量字符串&s2) { 返回s1.size()
编译时会显示:“错误调用非constexpr函数”您不能从C++ C++;为什么可以';不能在constexpr函数中调用字符串大小函数 constexpr bool isShorter(常量字符串&s1,常量字符串&s2) { 返回s1.size(),c++,string,c++11,size,constexpr,C++,String,C++11,Size,Constexpr,编译时会显示:“错误调用非constexpr函数”您不能从constexpr函数内部调用非constexpr函数。从中可以看出,std::string::size()不是consteprstd::string::size()不是constepr 使用文字c字符串,您可以执行以下操作: constexpr bool isShorter(const string &s1, const string &s2) { return s1.size() <
constexpr
函数内部调用非constexpr
函数。从中可以看出,std::string::size()
不是constepr
std::string::size()
不是constepr
使用文字c字符串,您可以执行以下操作:
constexpr bool isShorter(const string &s1, const string &s2)
{
return s1.size() < s2.size();
}
模板
constexpr bool isShorter(const char(&)[N1],const char(&)[N2])
{
返回N1
string
可以使用动态内存分配,这使得它从根本上说是非constexpr。如果不了解系统的其余部分,这个函数似乎毫无意义。为什么希望使用isShorter(s1,s2),这需要用户知道当s1.size()template <std::size_t N1, std::size_t N2>
constexpr bool isShorter(const char (&)[N1], const char (&)[N2])
{
return N1 < Ns;
}