竟然還有這樣使用的auto

今天學習了一下keyword,無心中發現了本身一直不曾接觸到的autohtml

好吧,我又開始胡扯了!ios

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. (不曾發現這點)api

1.大致意思講解了auto的使用方式(除了函數),函數

2.(大學四年四級未過,今年我不考了)大致意思(在函數聲明中,auto關鍵字不能用做函數返回的類型,它僅僅可以做爲返回細節符號的一部分。。。)oop

 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)學習

相關文章
相關標籤/搜索