-
-
Notifications
You must be signed in to change notification settings - Fork 617
Expand file tree
/
Copy pathdecltype.cpp
More file actions
69 lines (57 loc) · 1.56 KB
/
decltype.cpp
File metadata and controls
69 lines (57 loc) · 1.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
// https://cirosantilli.com/linux-kernel-module-cheat#cpp-decltype
#include <cassert>
#include <vector>
#include <utility> // declval
int f() {
return 1;
}
class C {
public:
int f() { return 2; }
};
int i;
decltype(i) g() {
return 1;
}
int main() {
#if __cplusplus >= 201103L
// Implies reference while auto does not.
{
int i = 0;
int& ir = i;
decltype(ir) ir2 = ir;
ir2 = 1;
assert(i == 1);
}
// Can be used basically anywhere.
{
int i = 0;
std::vector<decltype(i)> v;
v.push_back(0);
}
// Return value.
{
decltype(f()) i;
assert(typeid(i) == typeid(int));
C c;
decltype(c.f()) j;
assert(typeid(j) == typeid(int));
// Return value without instance. Use declval.
// http://stackoverflow.com/questions/9760358/decltype-requires-instantiated-object
decltype(std::declval<C>().f()) k;
assert(typeid(k) == typeid(int));
}
// decltype must take expressions as input, not a type.
// For types with the default constructor like `int`, we can just call the default constructor as in int():
// https://stackoverflow.com/questions/39279074/what-does-the-void-in-decltypevoid-mean-exactly
// or we can just use declval.
{
decltype(int()) i = 0;
assert(typeid(i) == typeid(int));
decltype(std::declval<int>()) j = 0;
assert(typeid(j) == typeid(int));
}
// Can be used to declare the return value of functions.
assert(g() == 1);
#endif
}