C++11 学习笔记-类型推导

auto类型推导

  auto关键字主要有两种用途:  
- 在变量声明时根据初始化列表表达式自动推断该变量的类型
- 声明函数时作为函数返回值的占位符
注意事项:
- 使用auto声明的变量必须马上初始化
- 函数参数和模板参数不能被声明为auto
- 对于数组类型,auto关键字会推导为指针类型,除非被声明为引用
- 在结构体中,auto不能用于非静态变量

struct{
    auto a = 10; //错误,不能用于非静态变量
    static const auto b = 2; //ok
}

template<class T, class U>
void add(T t, U u)
{
    auto s = t + u;
    cout << "type of t + u is " << typeid(s).name() << endl;
}

//函数返回值占位符,配合decltype使用,返回类型后置语法
template<class T, class U>
auto add(T t, U u) -> decltype(t + u) 
{
    return t + u;
}

int main()
{
    // 简单自动类型推断
    auto a = 123;
    cout << "type of a is " << typeid(a).name() << endl;  //int
    auto s("fred");
    cout << "type of s is " << typeid(s).name() << endl; //string

    // 冗长的类型说明(如迭代器)
    vector<int> vec;
    auto iter = vec.begin();
    cout << "type of iter is " << typeid(iter).name() << endl;
}

推导规则:
1. 当不声明为指针或者引用时,auto的推导结果和初始化表达式抛弃引用和CV限定符后类型一致。
2. 当声明为指针或者引用时,auto的推导结果将保持初始化表达式的CV属性。

    auto a = 10;
    auto *pa = new auto(a);
    auto **rpa = new auto(&a);
    cout << typeid(a).name() << endl;   // 输出: int
    cout << typeid(pa).name() << endl;  // 输出: int *
    cout << typeid(rpa).name() << endl; // 输出: int **

    int x = 0; 
    auto *a = &x; // a->int*, auto被推导为int
    auto b = &x; //b->int* ,auto被推导为int*
    auto &c = x; // c->int&, auto被推导为int
    auto d = c; //c->int, auto被推导为int  不声明为指针或者引用时,auto的推导结果和初始化表达式抛弃引用和CV限定符后类型一致
    const auto e = x; //e->const int 
    auto f = e; //e->int
    const auto& g = x; //g->const int&
    auto &h = g; //h->const int&

decltype类型推导

   decltype用来在编译时推导出一个变量类型。
decltype(exp)的推导规则:
1、exp是标识符,类访问表达式,decltype(exp)和exp类型一致
2、exp是函数调用,decltype(exp)与返回值类型一致。
3、其他情况,若exp是一个左值,则decltype(exp)是exp类型的左值引用,否则与exp类型一致。
4、decltype可以保留住表达式的引用以及CV限定符。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值