constexpr的用法

我的观点:今天有幸看到各位大神们在讨论constexpr的前途,有人说vs2010、2011、2012、2013都不支持,所以就觉得没用。好吧,我的世界中vs并不是不可获取,好吧,自己为了口头的胜利开始胡扯了。constexpr就像是一个告诉编译器,this is a const XXtype.但是各种有趣的实验证明了这个玩意还是有用的。

我来给你们验证一下:

1.如数一个数字,计算出它的!的结果(忘记叫什么了eg:5!==5*4*3*2*1==120)

 1 //build-1234-Desktop_Qt_5_3_MinGW_32bit-Debug
 2 #include <iostream>
 3 constexpr int fact(int n)
 4 {
 5     return n<2?1:(n*fact(n-1));
 6 }
 7 constexpr int fact2(int n){
 8     return n<2?1:(n*fact(n-1));
 9 }
10 template<int n>class print{
11 public:
12     print(){std::cout<<n<<'\t';}
13 };
14 int main()
15 {
16     std::cout<<fact(5)<<'\t'<<fact2(6)<<std::endl;
17     print<fact(5)> out1;
18     print<fact2(6)> out2;
19     return 0;
20 }
21 //output
22 /**
23 120     720
24 120     720
25 */

本例也就是constexpr最基本的功能,可以使一个函数转化成一个基本类型一样的类型。使C++看起来更加完善

甚至可以把上面的例子中修改为print(){std::cout<<(char)n<<'\t';}

2、可以用在一些不需要修改的地方,防止修改。(const)

 

 1 //build-1234-Desktop_Qt_5_3_MinGW_32bit-Debug
 2 #include <iostream>
 3 #include <stdexcept>
 4 
 5 class conststr{//定义一个const string类
 6     const char* p;
 7     std::size_t N;
 8 public:
 9     template<std::size_t Num>
10     constexpr conststr(const char(&a)[Num]):p(a),N(Num-1){}
11     constexpr char operator[](std::size_t n){//后面有用
12         return n<N?p[n]:throw std::out_of_range("");
13     }
14     constexpr std::size_t size(){
15         return N;
16     }
17 };
18 constexpr std::size_t countlower(conststr s,std::size_t c=0,std::size_t n=0){//计算'a'<X>'z'
19     return n==s.size()?c:
20                        s[n]>='a'&& s[n]<='z'?
21                            countlower(s,c+1,n+1):countlower(s,c,n+1);
22 }
23 
24 int main()
25 {
26     std::cout<<countlower("hello,world")<<std::endl;
27     std::cout<<countlower("hello,world___and___it")<<std::endl;
28     return 0;
29 }
30 //output
31 /**
32 10
33 15
34 */

 

本文参考地方:http://tool.oschina.net/apidocs/apidoc?api=cpp%2Fen%2Fcpp.html

 

转载于:https://www.cnblogs.com/cnblogs-maxlleric/p/4131883.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值