码迷,mamicode.com
首页 > 其他好文 > 详细

constexpr的用法

时间:2014-11-29 21:37:24      阅读:544      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   http   io   ar   color   os   sp   

我的观点:今天有幸看到各位大神们在讨论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

 

constexpr的用法

标签:des   style   blog   http   io   ar   color   os   sp   

原文地址:http://www.cnblogs.com/cnblogs-maxlleric/p/4131883.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!