mercredi 22 avril 2020

How constexpr deduces the value?

I was going through the program mentioned in cppreference.com for LiteralTypes. (https://en.cppreference.com/w/cpp/named_req/LiteralType)

I know that constexpr deduces the value during compile time. But in the below case line 10, 12 and 16 doesn't know the input parameters directly. (at least I can't make out)

Then how is it deducing the value?

  1 #include <iostream>
  2 #include <stdexcept>
  3 
  4 class conststr
  5 {
  6     const char* p;
  7     std::size_t sz;
  8 public:
  9     template<std::size_t N>
 10     constexpr conststr(const char(&a)[N]) : p(a), sz(N - 1) {}
 11 
 12     constexpr char operator[](std::size_t n) const
 13     {
 14         return n < sz ? p[n] : throw std::out_of_range("");
 15     }
 16     constexpr std::size_t size() const { return sz; }
 17 };
 18 
 19 constexpr std::size_t countlower(conststr s, std::size_t n = 0,
 20                                              std::size_t c = 0)
 21 {
 22     return n == s.size() ? c :
 23            s[n] >= 'a' && s[n] <= 'z' ? countlower(s, n + 1, c + 1) :
 24                                         countlower(s, n + 1, c);
 25 }
 26 
 27 // output function that requires a compile-time constant, for testing
 28 template<int n>
 29 struct constN
 30 {
 31     constN() { std::cout << n << '\n'; }
 32 };
 33 
 34 int main()
 35 {
 36     std::cout << "the number of lowercase letters in \"Hello, world!\" is ";
 37     constN<countlower("Hello, world!")>(); // implicitly converted to conststr
 38 }

Aucun commentaire:

Enregistrer un commentaire