Default Template Parameters and Template Instantiation

Let’s discuss default template parameters, template instantiation, and a compiler-time feature.

Default template parameters

Sometimes, it is cumbersome to provide template parameter types every time a template is used, especially when that type is almost always a particular type. For example, getResponse() may almost always be called for the int type in the program, and only in a few places for the double type.

It is possible to specify default types for template parameters, which are assumed when the types are not explicitly provided. Default parameter types are specified after the = character:

T getResponse(T = int)(string question) {
    // ...
}
// ...
    auto age = getResponse("What is your age?");

Get hands-on with 1400+ tech skills courses.