C++ 语言篇 constexpr

指定变量或函数的值能出现在常量表达式中[c++11]

细节

  • C++11 constexpr 函数使用递归而非迭代
  • constexpr 函数必须用条件运算符?:来抛异常,提示错误
  • constexpr声明的函数,必须把一切放在单条 return 语句中。
  • 使用volatile的时候,不允许优化,只能在运行时计算。

Example

Definition of a C++11 constexpr function which computes factorials and a literal type that extends string literals:

1
2
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
58
59
60
61
#include <iostream>
#include <stdexcept>

// C++11 constexpr functions use recursion rather than iteration(C++11 constexpr 函数使用递归而非迭代)
// (C++14 constexpr functions may use local variables and loops)(C++14 constexpr 函数可使用局部变量和循环)
constexpr int factorial(int n)
{
return n <= 1 ? 1 : (n * factorial(n - 1));
}

// literal class
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 functions signal errors by throwing exceptions
// in C++11, they must do so from the conditional operator ?:
// constexpr 函数通过抛异常来提示错误
// C++11 中,它们必须用条件运算符?:这么做
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; }
};

// C++11 constexpr functions had to put everything in a single return statement.constexpr声明的函数,必须把一切放在单条 return 语句中。
// (C++14 doesn't have that requirement)
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);
}
//这个函数的功能是计算小写字母的数字。

// output function that requires a compile-time constant, for testing
template<int n>
struct constN
{
constN() { std::cout << n << '\n'; }
};

int main()
{
std::cout << "4! = " ;
constN<factorial(4)> out1; // computed at compile time
//在编译的时候已经计算好了constN<24> out1;

volatile int k = 8; // disallow optimization using volatile
std::cout << k << "! = " << factorial(k) << '\n'; // computed at run time
//使用volatile的时候,不允许优化,只能在运行时计算。

std::cout << "the number of lowercase letters in \"Hello, world!\" is ";
constN<countlower("Hello, world!")> out2; // implicitly converted to conststr
//"Hello, world!"隐式转换到conststr
}

Output:

1
2
3
4! = 24
8! = 40320
the number of lowercase letters in "Hello, world!" is 9

to be continued…

Thanks for Support.