使用auto进行类型推导
#include<iostream>
using namespace std;
int main()
{
const int i = 42;
auto j = i;
j = 1;
cout<<j<<endl; // auto一般会忽略顶层const
const auto &k = i; // 明确指定为顶层const
//k = 1; // k是const引用
auto *p = &i; // p的类型是const int*
//int* pp = &i; // invalid conversion from const int* to int*
//*pp = 1;
p = 0;
*p = 1;
const auto j2 = i, &k2 = i; // 同上
return 0;
}
使用decltype进行类型推导
在需要从表达式的类型推断出要定义的变量的类型,但是又不希望用表达式的值初始化要定义的变量时,可以用decltype。
如下
//important
#include<iostream>
using namespace std;
int main()
{
int a = 3, b = 4;
decltype(a) c = a;
decltype(a = b) d = a; // decltype并不会实际执行表达式 ,注意a=b的赋值操作产生引用类型
// 产生的原因应该是内置的=操作符返回的是引用类型
cout<<c<<endl;
cout<<d<<endl;
cout<<a<<endl; // 表达式实际上没有被执行,a的值没有发生变化
d = 1;
cout<<a<<endl; // d是a的引用
cout<<d<<endl;
return 0;
}
输出:

在对拥有顶层const的变量进行类型推导时,auto和decltype的表现有所不一样,具体的,auto会忽略顶层const而decltype会保留顶层const。代码如下
// important
// decltype推断时是否会忽略顶层const属性?
#include<iostream>
using namespace std;
int main()
{
const int a = 2;
auto b = a; // b是int类型 ,auto忽略了顶层const
decltype(a) c = 5; // c是const int类型,decltype保留了顶层const
b = 8;
//c = 9; // 错误 assignment of read-only variable 'c'
return 0;
}
本文探讨了C++中auto和decltype两种类型推导方式的差异。通过示例代码展示它们在处理顶层const时的不同行为,以及在变量声明和表达式类型推导中的应用。auto通常忽略顶层const,而decltype会保留。此外,还解释了decltype如何根据表达式类型而非实际赋值来推导变量类型。

983

被折叠的 条评论
为什么被折叠?



