Template Instantiation and Template Specializations
Learn about template instantiation and template specializations in this lesson.
We'll cover the following
Template instantiation
Automatic code generation for a specific set of template parameter values is called an instantiation of that template for that specific set of parameter values. For example, to!string
and to!int
are two different instantiations of the to
function template.
As we will mention again in a separate section below, distinct instantiations of templates produce distinct and incompatible types.
Template specializations
Although the getResponse()
function template can, in theory, be used for any template type, the code that the compiler generates may not be suitable for every type. Let’s assume that we have the following type that represents points on a two-dimensional space:
struct Point {
int x;
int y;
}
Although the instantiation of getResponse()
for the Point
type itself would be fine, the generated readf()
call for Point
cannot be compiled. This is because the standard library function readf()
does not know how to read a Point
object. The two lines that actually read the response would look like the the Point
instantiation of the getResponse()
function template below:
Get hands-on with 1400+ tech skills courses.