The (not so new anymore) C++11 standard introduced the extern
keyword for templates. Its purpose is to tell the compiler that a template should not be instantiated at the point of usage, but that it will be instantiated in another translation unit (and thus there will be an instantiation available at link time) - at least AFAIK.
Now, even in the pre-C++11 era we used something similar to separate the declaration/definition of template classes from its instantiation in order to speed up compilation, e.g. like so:
point.h: class definition
template <int dim> struct Point {
...
void foo();
...
};
point.cpp: method definitions
#include "point.h"
template <int dim>
void Point<dim>::foo() {
...
}
point_2d.cpp: class instantiation (2D version)
#include "point.cpp"
template struct Point<2>;
point_3d.cpp: class instantiation (3D version)
#include "point.cpp"
template struct Point<3>;
main.cpp: usage of 2D and 3D points
#include "point.h"
int main(int, char**) {
Point<2> p;
p.foo();
}
Now I am wondering:
- Is our approach valid C++ (03 or 11) code or are we just lucky it worked?
- With C++11, would we be able to achieve the same thing by including
point.cpp
inmain.cpp
and declaringextern template <int dim> struct Point;
?