Are you familiar with the difference between Generics in languages like Java and C#, and Templates in C++ ? Functionally they serve the same purpose, to dynamically type a class, but they are actually quite different, and may not be implemented as you might expect.
Let’s start with Generics. In languages like Java and C#, you can declare a class like so:
public class Foo<T>
{
private T _bar:
public Foo(T bar)
{
_bar = bar;
}
}
Doing so will force the consumer of this class to specify its type like so:
Foo<T> myFoo = new Foo<T>("Stringly typed!");
The type is enforced to be ‘String’ in this case. But is the enforcement at compile time or runtime? You might be surprised to learn that it is at compile time. It is nothing more than compile-time convention to force the programmer to be type-safe. The actual objects at run-time have no notion that they can or cannot be a certain type, and are simply expected to be properly enforced at compile time.
So now that we understand how they work in Java and C#, what about Templates in C++? They serve a very similar purpose, but how are they actually implemented compared to the other languages? It turns out that at compile-time C++ will actually generate all possible combinations of the template based on the possible types that could be passed to it as determined by the compiler looking at the rest of the code. This makes sense, since the name of the feature is ‘template’, but it’s not often thought about in that fashion by average C++ developers.