C++:constexpr用法

[复制链接]
 楼主| keer_zu 发表于 2023-3-7 14:32 | 显示全部楼层 |阅读模式
ST, TE
constexpr是c++11新添加的特征,目的是将运算尽量放在编译阶段,而不是运行阶段。这个从字面上也好理解,const是常量的意思,也就是后面不会发生改变,因此当然可以将计算的过程放在编译过程。constexpr可以修饰函数、结构体。
 楼主| keer_zu 发表于 2023-3-7 14:33 | 显示全部楼层
修饰函数

    • 修饰的函数只能包括return 语句。
    • 修饰的函数只能引用全局不变常量。
    • 修饰的函数只能调用其他constexpr修饰的函数。
    • 函数不能为void 类型和,并且prefix operation(v++)不允许出现。


下面通过一个例子来进一步说明:
  1. // 通过对斐波拉契函数的递归实现,来看看constexpr具体怎么修饰函数,同时比较这样使用的好处
  2. #include<iostream>
  3. #include<time.h>
  4. using namespace std;
  5. //在这个函数里面,由于constexpr稀释的是fib1这个函数,因此每一次计算的结果都会作为一个常量保存下来
  6. //这个实现的复杂度等同于迭代的方法,基本上为O(n)。
  7. constexpr long int fib1(int n)
  8. {
  9.         return (n <= 1)? n : fib1(n-1) + fib1(n-2); //只能包含一个retrun语句
  10. }
  11. //熟悉递归函数就不难证明下面这个函数的时间复杂度为O(2^n)
  12. long int fib2(int n){
  13.         return (n <= 1)? n : fib(n-1) + fib(n-2);
  14. }
  15. int main ()
  16. {
  17.         // value of res is computed at compile time.
  18.           clock_t start, end;
  19.           start = clock();
  20.         const long int res = fib1(30);
  21.           end = clock();
  22.           cout << "Totle Time fib1 : " <<(double)(end - start) / CLOCKS_PER_SEC << "s" << endl;
  23.           start = clock();
  24.         const long int res = fib2(30);
  25.           end = clock();
  26.           cout << "Totle Time fib2 : " <<(double)(end - start) / CLOCKS_PER_SEC << "s" << endl;
  27.         cout << res;
  28.         return 0;
  29. }



 楼主| keer_zu 发表于 2023-3-7 14:33 | 显示全部楼层
修饰结构体:


  1. // C++ program to demonstrate uses of constexpr in constructor
  2. #include <bits/stdc++.h>
  3. using namespace std;
  4. // A class with constexpr constructor and function
  5. class Rectangle
  6. {
  7. int _h, _w;
  8. public:
  9.         // 修饰一个结构体
  10.         constexpr Rectangle (int h, int w) : _h(h), _w(w) {}
  11.         // 修饰一个函数,_h, _w为全局,并且在实例化时就已经是初始化后的常量了
  12.         constexpr int getArea () { return _h * _w; }
  13. };
  14. int main()
  15. {
  16.         // 对象在编译时就已经初始化了
  17.         constexpr Rectangle obj(10, 20);
  18.         cout << obj.getArea();
  19.         return 0;
  20. }


您需要登录后才可以回帖 登录 | 注册

本版积分规则

个人签名:qq群:49734243 Email:zukeqiang@gmail.com

1478

主题

12912

帖子

55

粉丝
快速回复 在线客服 返回列表 返回顶部
个人签名:qq群:49734243 Email:zukeqiang@gmail.com

1478

主题

12912

帖子

55

粉丝
快速回复 在线客服 返回列表 返回顶部