Take a look at GW

【C++】C++中typedef、auto与decltype的作用

typedef

类型别名(type alias)是一个名字,使用typedef不会真正地创建一种新的数据类型,它只是已经存在数据类型的一个新名称。
语法:

typedef type name;

其中type是c++中的数据类型,name是这个类型的一个别名。

C++11提供了引用的功能,关于引用的详细介绍可以参考笔者之前的文章。引用为变量提供别名,typedef则是为类型提供别名。

例如:

#include <iostream>
int main(){
    int m = 10;//使用int定义变量m
    typedef int integer;//创建一个int的别名为integer
    integer n = 20;//使用integer定义变量n
    typedef integer integer_type;//创建一个integer的别名为integer_type
    integer_type o = 30;//使用integer_type定义变量o
    std::cout << "m + n + o = " << (m+n+o) << std::endl;//运算
    return 0;
}

输出结果:

m + n + o = 60

上面有两个别名integer和integer_type,integer_type有integer创建而来,integer_type和integer都是属于int类型。

c++11还为提供别名提供了另一种更为简便的方法—别名声明(alias declaration),例如:

using integer = int; // integer是int的同义词

这种方法的规则是用using关键字作为别名的开始,其后紧跟别名和等号。

 

auto

auto是c++11标准定义的一个类型推断的关键字,auto能够让编译器自动去分析表达式所属的类型,与特定的数据类型不同(比如double),让编译器通过初始值来推算变量的类型。显然auto定义必须有初始值。
比如:

#include <iostream>
#include <typeinfo>
#include <set>
using namespace std;

int main()
{
auto x = 4;
auto y = 3.37;
auto ptr = &x;
cout << "x type is : " << typeid(x).name() << endl
 << "y type is : " << typeid(y).name() << endl
 << "ptr type is : " << typeid(ptr).name() << endl;

cout << "--------------------------" << endl;

set<string> strs;
strs.insert({"green","blue","red"});
for(auto it = strs.begin();it != str.end();it++){//遍历容器中的元素
    cout << *it << " ";
}

cout << "--------------------------" << endl;

//r是一个int引用类型
auto &r = x;
cout << "r type is : " << typeid(r).name() << endl;

return 0;
}

输出结果:

x type is : i
y type is : d
ptr type is : Pi
--------------------------
blue green red
--------------------------
r type is : i

上面的i表示int,d表示double,Pi表示int*(int类型的指针)。

decltype

decltype也是c++11提供的一个关键字,它可以从变量或表达式中提取类型。

int f() { return 10; }
int main(){
    decltype(f()) val;//f()返回值是int类型,val是int类型

    const int &v = 10;
    decltype(v) rval;//错误,rval 是引用类型,必须要初始化

    int pv = 10;
    int *p = &pv;
    decltype(p) pp;//正确,pp是int*类型。
    decltype(*p) c;//错误,c是int&类型(int引用类型),必须要初始化
    return 0;
}

如果表达式是解引用操作(*),那么decltype将会得到引用类型。如上面的decltype(*p)。

如果decltype里面有两个括号,那么是一个引用类型

decltype((i)) d;//错误,d是int&,必须要初始化。
decltype(i) e;//正确,e是一个(未初始化)int。

 

注意:

decltype((variable))(注意是双括号)的结果永远是引用,而decltype(variable)结果只有当variable本身是引用时才是引用。

posted @ 2019-01-10 14:59  HDWK  阅读(846)  评论(0编辑  收藏  举报