auto
auto的自动类型推导,用于从初始化表达式中推断出变量的数据类型。从这个意义上讲,auto并非一种“类型”声明,而是一个类型声明时的“占位符”,编译器在编译时期会将auto替换为变量实际的类型。
通过auto的自动类型推导,可以大大简化我们的编程工作:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
double foo() {}
void func(vector<string> & tmp)
{
for (auto i = tmp.begin(); i < tmp.end(); i++)
{
// 一些代码
}
}
int main()
{
auto x = 1; // x的类型为int
auto y = foo(); // y的类型为double
struct m { int i; }str;
auto str1 = str; // str1的类型是struct m
auto z; // err, 无法推导,无法通过编译
z = x;
return 0;
}
注意点:
void fun(auto x =1) {} // 1: auto函数参数,有些编译器无法通过编译
struct str
{
auto var = 10; // 2: auto非静态成员变量,无法通过编译
};
int main()
{
char x[3];
auto y = x;
auto z[3] = x; // 3: auto数组,无法通过编译
// 4: auto模板参数(实例化时),无法通过编译
vector<auto> x = {1};
return 0;
}
decltype
decltype实际上有点像auto的反函数, auto可以让你声明一个变量,而decltype则可以从一个变量或表达式中得到其类型,如下:
#include <typeinfo>
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int i;
decltype(i) j = 0;
cout << typeid(j).name() << endl; // 打印出"i", g++表示integer
float a;
double b;
decltype(a + b) c;
cout << typeid(c).name() << endl; // 打印出"d", g++表示double
vector<int> vec;
typedef decltype(vec.begin()) vectype; // decltype(vec.begin()) 改名为 vectype
vectype k; // 这是auto无法做到的
//decltype(vec.begin()) k; // 这是auto无法做到的
for (k = vec.begin(); k < vec.end(); k++)
{
// 做一些事情
}
enum {Ok, Error, Warning}flag; // 匿名的枚举变量
decltype(flag) tmp = Ok;
return 0;
}
追踪返回类型
返回类型后置:在函数名和参数列表后面指定返回类型。
int func(int, int);
auto func2(int, int) -> int;
template<typename T1, typename T2>
auto sum(const T1 & t1, const T2 & t2) -> decltype(t1 + t2)
{
return t1 + t2;
}
template <typename T1, typename T2>
auto mul(const T1 & t1, const T2 & t2) -> decltype(t1 * t2)
{
return t1 * t2;
}
int main()
{
auto a = 3;
auto b = 4L;
auto pi = 3.14;
auto c = mul( sum(a, b), pi );
cout << c << endl; // 21.98
return 0;
}