forked from cirosantilli/cpp-cheat
-
Notifications
You must be signed in to change notification settings - Fork 0
/
decltype.cpp
63 lines (50 loc) · 1.11 KB
/
decltype.cpp
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
/*
# decltype
C++11 keyword
Replace decltype with type of an expression at compile time.
More powerful than `auto`.
*/
#include "common.hpp"
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(i) == 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));
}
// Can be used to declare the return value of functions.
assert(g() == 1);
#endif
}