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

居然还有这样使用的auto

时间:2014-11-29 22:51:25      阅读:210      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   ar   color   os   使用   sp   

今天学习了一下keyword,无意中发现了自己一直未曾接触到的auto

好吧,我又开始胡扯了!

automatic storage duration. (deprecated)
1) When declaring variables in block scope, in namespace scope, in init statements of for loops, etc, the type of the variable may be omitted and the keyword auto may be used instead. Once the type of the initializer has been determined, the compiler determines the type that will replace the keyword auto as if using the rules for template argument deduction from a function call. The keyword auto may be accompanied by modifies, such as const or &, which will participate in the type deduction. For example, given const auto& i = expr;, the type if i is exactly the type of the argument u in an imaginary template template<class U> void f(const U& u) if the function call f(expr) was compiled.
2) In a function declaration, the keyword auto does not perform automatic type detection. It only serves as a part of the trailing return type
syntax. (未曾发现这点)

1.大体意思讲解了auto的使用方式(除了函数),

2.(大学四年四级未过,今年我不考了)大体意思(在函数声明中,auto关键字不能用作函数返回的类型,它仅仅能够作为返回细节符号的一部分。。。)

 1 #include <iostream>
 2 #include <cmath>
 3 #include <typeinfo>
 4 template<class T,class U>
 5 auto add(T t,U u)->decltype(t+u)//一种符号的一部分,这样理解不会错把。。
 6 {
 7     return t+u;
 8 }
 9 //来个变态的
10 auto get_fun(int argc)->double(*)(double)//返回一种函数,这种函数double x(double),因为要地址,所以使用*
11 {
12     switch (argc) {
13     case 1:
14         return std::fabs;
15     case 2:
16         return std::sin;
17     default:
18        return std::cos;
19     }
20 }
21 int main()
22 {
23     auto a=add(1,2.54);
24     std::cout<<typeid(a).name()<<std::endl;
25     auto b=add(1,A);
26     std::cout<<typeid(b).name()<<std::endl;
27 
28     auto p=get_fun(2);
29     std::cout<<p(3.14)<<std::endl;//cos(3.14)
30 }
31 //output
32 /**
33 d----------->double
34 i------------>int(转换为int了)
35 0.00159265---------->==0
36 */

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

居然还有这样使用的auto

标签:style   blog   http   io   ar   color   os   使用   sp   

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

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