Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Templates with Default Type Parameters | Class Templates
C++ Templates
course content

Course Content

C++ Templates

C++ Templates

1. Creating First Template
2. Templates Usage
3. Class Templates
4. Template Specialization

bookTemplates with Default Type Parameters

It is possible to specify a default parameter type for a class template and starting from C++11, default template arguments can also be used in function templates. To set a default type, simply write the desired type after the equal sign for the template parameter.

cpp

main

copy
123456789101112131415
#include <iostream> template <typename T = int> // `int` will be used as a default type class Box { T value; // Stores the value of type `T` public: Box(T value) : value(value) { std::cout << this->value; } }; int main() { // Type not specified // VV Box<> intBox(25.5); }

When you run the code above, the output will be 25 instead of 25.5. This happens because the default type for the Box class is set to int, which truncates the decimal part of the value.

Note

Similar to default function arguments, if one template parameter has a default argument, then all template parameters following it must also have default arguments.

In addition to default type parameters, C++ allows for non-type template parameters with default values. Non-type parameters can be integral types, pointers, or references. To specify a non-type default parameter, you simply assign a default value after the parameter.

h

array

copy
123456
// `int` and `10` are default parameters template <typename T = int, size_t Size = 10> struct Array { T arr[Size]; // Array with a fixed size of `Size` }

Default template parameters simplify code, reduce redundancy, and enable templates to handle typical use cases with minimal effort while allowing customization when needed.

When a template parameter has a default value, which of the following is true?

When a template parameter has a default value, which of the following is true?

Select a few correct answers

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 3. Chapter 3
some-alt