您的位置:首页 > 其它

居然还有这样使用的auto

2014-11-29 21:29 267 查看
今天学习了一下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关键字不能用作函数返回的类型,它仅仅能够作为返回细节符号的一部分。。。)

#include <iostream>
#include <cmath>
#include <typeinfo>
template<class T,class U>
auto add(T t,U u)->decltype(t+u)//一种符号的一部分,这样理解不会错把。。
{
return t+u;
}
//来个变态的
auto get_fun(int argc)->double(*)(double)//返回一种函数,这种函数double x(double),因为要地址,所以使用*
{
switch (argc) {
case 1:
return std::fabs;
case 2:
return std::sin;
default:
return std::cos;
}
}
int main()
{
auto a=add(1,2.54);
std::cout<<typeid(a).name()<<std::endl;
auto b=add('1','A');
std::cout<<typeid(b).name()<<std::endl;

auto p=get_fun(2);
std::cout<<p(3.14)<<std::endl;//cos(3.14)
}
//output
/**
d----------->double
i------------>int(转换为int了)
0.00159265---------->==0
*/



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

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: