The Enigma
The Enigma

Reputation: 147

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();
   }

When compiled it says: "error call to non-constexpr function"

Upvotes: 1

Views: 212

Answers (2)

Jarod42
Jarod42

Reputation: 217930

std::string::size() is not constexpr

With literal c-string you may do:

template <std::size_t N1, std::size_t N2>
constexpr bool isShorter(const char (&)[N1], const char (&)[N2])
{
    return N1 < Ns;
}

Upvotes: 1

Paolo M
Paolo M

Reputation: 12777

You can't call a non-constexpr function from inside a constexpr one. And, as you can see from here, std::string::size() is not constexpr.

Upvotes: 1

Related Questions