auto和decltype
1、auto
auto的限制:
-
auto 不能在函数的参数中使用。
-
auto 不能作用于类的非静态成员变量(也就是没有 static 关键字修饰的成员变量)中。
-
auto 关键字不能定义数组
-
auto 不能作用于模板参数
2、decltype
用法:decltype(exp) varname = value;
如:
int a = 0;
decltype(a) b = 1; //b 被推导成了 int
decltype(10.8) x = 5.5; //x 被推导成了 double
decltype(x + 100) y; //y 被推导成了 double
exp 中调用函数时需要带上括号和参数,但这仅仅是形式,并不会真的去执行函数代码
3、返回值类型后置
auto和decltype结合使用得到返回类型
如:
#include <iostream>
int& foo(int i)
{
return i;
}
float foo(float& i)
{
return i + 0.1;
}
template<typename T>
//C++11中出现了新的用法:拖尾返回类型、auto 与 decltype 配合
auto foo_func(T& t)->decltype(foo(t))
{
return foo(t);
}
int main()
{
int a = 1;
auto c = foo_func<int>(a);
}