-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path02-5-extern-templates.cpp
More file actions
119 lines (91 loc) · 1.83 KB
/
Copy path02-5-extern-templates.cpp
File metadata and controls
119 lines (91 loc) · 1.83 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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
#include <iostream>
using namespace std;
// math.h - assume this lib
template<typename T>
T square(T x) {
return x * x;
}
/*
Now imagine three different files
- main.cpp
- utils.cpp
- tests.cpp
*/
// all of them include
#include "math.h"
// and all of them use
int res = square<int>(5);
/*
Graphically:
main.cpp
------------
square<int>()
↓
Compiler creates
int square(int)
utils.cpp
------------
square<int>()
↓
Compiler creates
int square(int)
tests.cpp
------------
square<int>()
↓
Compiler creates
int square(int)
Then linker removes the duplicates!
The compiler already spent time generating the same template code three times
Now imagine heavy templates like:
vector<int>
vector<double>
vectorstring>
If 200 files include <vector>, every file may instantiate many of those templates.
Compilation becomes slower.
*/
// C++11 solution: extern template
//extern template int square<int>(int);
/*
main.cpp
------------
uses square<int>()
Compiler:
"I know it exists.
I won't generate it."
utils.cpp
------------
Compiler:
"I won't generate it."
tests.cpp
------------
Compiler:
"I won't generate it."
math.cpp
------------
Compiler:
Generate square<int>()
Only one file performs the expensive work.
*/
/*
Difference
template class MyClass<int>;
means Instantiate here
extern template class MyClass<int>;
means Do not instantiate it here, someone else will.
*/
// Nested templates
vector<vector<int>> res1;
vector<vector<int> > res2;
vector<
vector<int>
> res3;
// Weird example
template<bool T>
class MagicType {
bool magic = T;
};
vector<MagicType<(1 > 2)>> magic;
int main() {
return 0;
}