constexpr 说明符
constexpr - 指定变量或函数的值可以在常量表达式中出现
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 
 | #include <iostream>#include <stdexcept>
 
 
 
 constexpr int factorial(int n)
 {
 return n <= 1 ? 1 : (n * factorial(n - 1));
 }
 
 
 class conststr
 {
 const char* p;
 std::size_t sz;
 public:
 template<std::size_t N>
 constexpr conststr(const char(&a)[N]): p(a), sz(N - 1) {}
 
 
 
 constexpr char operator[](std::size_t n) const
 {
 return n < sz ? p[n] : throw std::out_of_range("");
 }
 
 constexpr std::size_t size() const { return sz; }
 };
 
 
 
 constexpr std::size_t countlower(conststr s, std::size_t n = 0,
 std::size_t c = 0)
 {
 return n == s.size() ? c :
 'a' <= s[n] && s[n] <= 'z' ? countlower(s, n + 1, c + 1) :
 countlower(s, n + 1, c);
 }
 
 
 template<int n>
 struct constN
 {
 constN() { std::cout << n << '\n'; }
 };
 
 int main()
 {
 std::cout << "4! = " ;
 constN<factorial(4)> out1;
 
 volatile int k = 8;
 std::cout << k << "! = " << factorial(k) << '\n';
 
 std::cout << "\"Hello, world!\" 里小写字母的个数是 ";
 constN<countlower("Hello, world!")> out2;
 }
 
 |