Skip to content

Commit 9032191

Browse files
committed
template_instantiation
1 parent 22a066f commit 9032191

File tree

7 files changed

+39
-0
lines changed

7 files changed

+39
-0
lines changed

cpp/README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,8 @@
6666
1. [Preprocessor](preprocessor.cpp)
6767
1. using
6868
1. using type alias. TODO http://en.cppreference.com/w/cpp/language/type_alias
69+
1. templates
70+
1. [template instantiation](template_instantiation/)
6971
1. [Standard library](standard_library.md)
7072
1. [Headers](common.hpp)
7173
1. [Containers](containers.md)

cpp/template_instantiation/Makefile

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
../../Makefile_one
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
CXX_STD = c++11

cpp/template_instantiation/README.md

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
Template instantiation saves us from infinite compilation times because whenever you modify a header, the build system (correctly) rebuilds everything that includes that header.
2+
3+
They can also save object size (and likely a little bit of time) because templates are re-instantiated for each object file, unless users mark it as extern on every file, which they won't remember to do
4+
5+
* https://stackoverflow.com/questions/8130602/using-extern-template-c11/59614090#59614090
6+
* https://stackoverflow.com/questions/2351148/explicit-instantiation-when-is-it-used
7+
* https://en.cppreference.com/w/cpp/language/class_template#Explicit_instantiation
8+
9+
We can also confirm with `nm -C` that the `main.o` object file does not contain a definition of `MyClass`, in that case because `MyClass` is not a complete definition because `f` is not defined.

cpp/template_instantiation/main.cpp

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
#include <iostream>
2+
3+
#include "notmain.hpp"
4+
5+
int main() {
6+
std::cout << MyClass<int>().f(1) << std::endl;
7+
#if 0
8+
// error: undefined reference to `X<float>::f(float)'
9+
std::cout << X<float>().f(1.5) << std::endl;
10+
#endif
11+
}
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
#include "notmain.hpp"
2+
3+
template<class T>
4+
T MyClass<T>::f(T t) { return t + 1; }
5+
6+
// Only int is instantiated.
7+
template class MyClass<int>;
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
#ifndef NOTMAIN_HPP
2+
#define NOTMAIN_HPP
3+
4+
template<class T> struct MyClass {
5+
T f(T t);
6+
};
7+
8+
#endif

0 commit comments

Comments
 (0)