auto用法

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

例子:

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; // d->int,auto被推导为int, (第一种情况)

const auto e = x; // e->const int (第一种情况)
auto f = e; // f->int (第一种情况)

const auto& g = x; // g->const int& (第二种情况)
auto& h = g; // h->const int& (第二种情况)

 二、auto的限制:

1)auto不能用于函数参数。
2)auto不能用于非静态成员变量。
3)auto无法定义数组。
4)auto无法推导出模板参数。

void func(auto a = 1) {}   // error: auto不能用于函数参数

struct Foo
{
    auto var1_ = 0;          // error: auto不能用于非静态成员变量。
    static const auto var2_ = 0;  // OK:var2_->static const int
};

template <typename T>
struct Bar {};

int main()
{
    int arr[10] = {0};
    auto aa = arr; // OK:aa->int*
    auto rr[10] =arr; // error:auto无法定义数组
    
    Bar<int> bar;
    Bar<auto> bb = bar;  // error: auto无法推导出模板参数。
    return 0;
}

 

posted @ 2022-09-02 23:37  一路同行12344  阅读(159)  评论(0编辑  收藏  举报