auto&decltype

auto name=value

自动补全 name 的类型。

decltype(value2) name=value1

value2 的类型赋予 name

小尝试:

1
2
3
4
5
6
7
8
9
10
11
12
#include<bits/stdc++.h>

using namespace std;

const int x=1;

int main()
{
decltype(x) a = 1;
a++;
cout<<typeid(a).name()<<endl;
}

代码报错,可见赋值结果是 const int

但是auto把一个变量赋值为一个常量的值是可以的

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include<bits/stdc++.h>

using namespace std;

const int x=1;

int main()
{
// decltype(x) a = 1;
// a++;
auto a=x;
a++;
cout<<typeid(a).name()<<endl;
}

不过两个 const 加起来 decltype 就报错失败了。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include<bits/stdc++.h>

using namespace std;

const int x=1;
const int y=1;

int main()
{
decltype(x+y) a = 1;
a++;
// auto a=x;
// a++;
cout<<typeid(a).name()<<endl;
}

此时又变成 int 。

补充一下参数输出结果:

类型 typeid输出
bool: b
char: c
signed char: a
unsigned char: h
(signed) short (int): s
unsigned short (int): t
(signed) (int): i
unsigned (int): j
(signed) long (int): l
unsigned long (int): m
(signed) long long (int): x
unsigned long long (int): y
float: f
double: d
long double: e

还有 is_lvalue_reference<x> 可以判断一个表达式是否为左值引用。is_same<x,y> 判断两者是否为一个类型。

std::function和lambda表达式