Skip to content

Commit c39ffb6

Browse files
committed
template_on_header
1 parent 9032191 commit c39ffb6

File tree

7 files changed

+38
-0
lines changed

7 files changed

+38
-0
lines changed

cpp/template_on_header/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_on_header/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_on_header/main.cpp

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
#include <iostream>
2+
3+
#include "mytemplate.hpp"
4+
#include "notmain.hpp"
5+
6+
int main() {
7+
std::cout << notmain() + MyTemplate<int>().f(1) << std::endl;
8+
}

cpp/template_on_header/mytemplate.hpp

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
#ifndef MYTEMPLATE_HPP
2+
#define MYTEMPLATE_HPP
3+
4+
template<class T>
5+
struct MyTemplate {
6+
T f(T t) { return t + 1; }
7+
};
8+
9+
#endif

cpp/template_on_header/notmain.cpp

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
#include "mytemplate.hpp"
2+
#include "notmain.hpp"
3+
4+
int notmain() { return MyTemplate<int>().f(1); }

cpp/template_on_header/notmain.hpp

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
#ifndef NOTMAIN_HPP
2+
#define NOTMAIN_HPP
3+
4+
int notmain();
5+
6+
#endif

0 commit comments

Comments
 (0)