auto&&decltype的区别

1.auto在做类型推断时用编译器计算变量的初始值推断类型;decltype则不实际计算表达式的值

2.编译器推断的auto类型优势可能与初始值类型不完全一样,编译器会适当改变结果类型使其更符合初始化规则

                 例如auto会忽略顶层const,保留底层const

   与之相反,decltype会保留变量顶层const.

3.与auto不同,decltype的结果类型与表达式姓氏密切相关,如果加括号,则得到的类型和不加括号时会有不同

#include <iostream>
#include<typeinfo>
using namespace std;
int main()
{
    int a = 3;
    auto c1 = a;
    decltype(a) c2 = a;
    decltype((a)) c3 = a;

    const int d = 5;
    auto f1 = d;
    decltype(d) f2= d;

    cout<<typeid(c1).name ()<<endl;
    cout<<typeid(c2).name ()<<endl;
    cout<<typeid(c3).name ()<<endl;
    cout<<typeid(f1).name ()<<endl;
    cout<<typeid(f2).name ()<<endl;

    c1++;
    c2++;
    c3++;
    f1++;
    //f2++; //error f2 is const type
    cout<<"a:"<<a<<" c1:"<<c1<<" c2:"<<c2<<" c3:"<<c3<<" f1:"<<f1<<" f2:"<<f2<<endl;

    return 0;
}

发布了156 篇原创文章 · 获赞 36 · 访问量 19万+

猜你喜欢

转载自blog.csdn.net/nh5431313/article/details/103968545