Effective Modern C++: constexpr

constexpr是C++11中新增的关键字,其语义是“常量表达式”,也就是在编译期可求值的表达式。最基础的常量表达式就是字面值或全局变量/函数的地址或sizeof等关键字返回的结果,而其它常量表达式都是由基础表达式通过各种确定的运算得到的。constexpr值可用于enum、switch、数组长度等场合。

constexpr所修饰的变量一定是编译期可求值的,所修饰的函数在其所有参数都是constexpr时,一定会返回constexpr。

constexpr还能用于修饰类的构造函数,即保证如果提供给该构造函数的参数都是constexpr,那么产生的对象中的所有成员都会是constexpr,该对象也就是constexpr对象了,可用于各种只能使用constexpr的场合。注意,constexpr构造函数必须有一个空的函数体,即所有成员变量的初始化都放到初始化列表中。

特性:

  • constexpr所修饰的对象一定具有const特性,但是const修饰的对象不一定都是constexpr.
  • constexpr所修饰的函数在编译时运行,因此可以提高软件的运行速度,尽可能多用constexpr.

示例代码:

 1 class Point {
 2 public:
 3     constexpr Point(double xVal=0, double yVal=0) noexcept: x(xVal), y(yVal){}
 4     constexpr double xValue() const {return x;}
 5     constexpr double yValue() const {return y;}
 6     void setX(double xVal) {x = xVal;}
 7     void setY(double yVal) {y = yVal;}
 8 
 9 private:
10     double x;
11     double y;
12 };
13 
14 constexpr Point midPoint(const Point& p1, const Point& p2){
15     return {(p1.xValue() + p2.xValue())/2, (p1.yValue() + p2.yValue())};
16 }
17 
18 int main()
19 {
20     Point pt1(2.3, 2.1);
21     Point pt2(-12.1, -19);
22     Point ptMid = midPoint(pt1, pt2);
23     cout << ptMid.xValue() << endl;
24     cout << ptMid.yValue() << endl;】
25     return 0;
26 }

在C++14中,constexpr还可以修饰void函数:

 1 class Point {
 2 public:
 3     constexpr Point(double xVal=0, double yVal=0) noexcept: x(xVal), y(yVal){}
 4     constexpr double xValue() const {return x;}
 5     constexpr double yValue() const {return y;}
 6     constexpr void setX(double xVal) {x = xVal;}
 7     constexpr void setY(double yVal) {y = yVal;}
 8 
 9 private:
10     double x;
11     double y;
12 };
13 
14 constexpr Point midPoint(const Point& p1, const Point& p2){
15     return {(p1.xValue() + p2.xValue())/2, (p1.yValue() + p2.yValue())};
16 }
17 
18 constexpr Point reflection(const Point& p){
19     Point ret;
20     ret.setX(- p.xValue());
21     ret.setY(- p.yValue());
22     return ret;
23 }
24 
25 int main()
26 {
27     Point pt1(2.3, 2.1);
28     Point pt2(-12.1, -19);
29     Point ptMid = midPoint(pt1, pt2);
30     cout << ptMid.xValue() << endl;
31     cout << ptMid.yValue() << endl;
32     Point ptReflection = reflection(ptMid);
33     cout << ptReflection.xValue() << endl;
34     cout << ptReflection.yValue() << endl;
35     return 0;
36 }

猜你喜欢

转载自www.cnblogs.com/Asp1rant/p/12339647.html