auto类型

auto的限制

auto不能用于函数参数;不支持auto类型非静态成员初始化;auto无法定义数组;auto无法推导出模板类型。

void func(auto k = 1);  //auto不能用于函数参数

struct Foo 
{
    auto var1_ = 0;     //auto不能用于非静态成员
    static const auto var2_ = 0;
};

template<typename T>
struct Bar{};


int main()
{
    int x = 5;

    auto y = x; //auto->int,y->int

    auto *a = &x;   //auto->int, a->int*

    auto b = &x;    //auto->int *, b->int*

    auto &c = x;    //auto->int; c->int&

    auto d = &c;    //auto->int*; d->int *

    const auto& g = x;  //auto->int&; g->const int&

    auto h = g; //auto->const int&; h->const int&
    //当申明指针或者引用时,auto的推导结果将保持初始化表达式的cv属性

    int arr[10] = { 0 };    
    auto cpArr = arr;   //auto->int *;cpArr->int *

    auto nextArr[10];   //auto无法定义数组

    Bar<int> bar;
    Bar<auto> bb = bar;   //auto无法推导出模板类型

    return 0;

}

auto的应用
1.无法知道变量应该被定义成什么 类型。

class  Foo
{
public:
    static int get()
    {
        return 0;
    }
};

class Bar
{
public:
    static const char* get()
    {
        return "0";
    }
};

template<typename T>
func<T>()
{
    auto val = T::get();

}
int main()
{
    func<Foo>();
    func<Bar>();

    return 0;
}

2.简化变量声明类型

int main()
{
    std::map<double, double> resultmap;

    std::map<double, double>::iterator it = resultmap.begin();

    for (; it != resultmap.end(); it++)
    {
        //do something
    }
    return 0;
}

上述代码中it的类型其实通过resultmap.begin()即可知道,因此声明可以简化如下

int main()
{
    std::map<double, double> resultmap;

    /*std::map<double, double>::iterator it = resultmap.begin();*/

    for (auto it = resultmap.begin() ;it != resultmap.end(); it++)
    {
        //do something
    }
    return 0;
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值