Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Basic Syntax of Template | Creating First Template
C++ Templates
course content

Course Content

C++ Templates

C++ Templates

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

bookBasic Syntax of Template

Creating a template is actually quite simple, and it's one of the easiest parts of using them. To start, you'll need to create either a function or a class. We will start with the function.

cpp

main

copy
123456
void MyFirstTemplate() { } int main() { MyFirstTemplate(); }

As you can see, there is a very simple function that does nothing for now. We can easily call it inside the main function. Your task now is to turn it into a template.

h

template

copy
123456789101112
// To create a template, you need to add code above the function or class // Start with the keyword `template` to indicate you're defining a template // template // Add angle brackets `<>`, this is list of the parameters for template // template < > // Inside of it has to be keyword `typename` and the name of it // template <typename Name> template <typename Name> void MyFirstTemplate() { }

Now, let's make it do something, like printing a message. Go ahead and call it inside the main function to see it in action.

cpp

main

copy
123456789101112
#include <iostream> template<typename Name> void MyFirstTemplate() { std::cout << "c<>definity" << std::endl; } int main() { MyFirstTemplate(); }

As you can see, an error arises when we try to call it as if it were a simple function. This is because it's no longer just a simple function. This is where the template parameter, specified inside the brackets after the keyword template, comes into play.

cpp

main

copy
12345678910111213
#include <iostream> // This essentioally creates an alias for a type we will use template<typename Name> // In our case the name of the type is Name void MyFirstTemplate() { std::cout << "c<>definity" << std::endl; } int main() { // In order to call the template function properly // We need to specify any type inside the brackets MyFirstTemplate<void>(); // This tells the template to use void as the type for Name }

Note

It doesn't matter what type you specify for this example, so you can change void to any type you want. However, specifying the type is mandatory.

For the MyFirstTemplate function template, it is not necessary to specify a name for the type parameter. You can remove Name, and everything will still work because the type parameter is not used inside the function.

What is the correct syntax for declaring a template function?

What is the correct syntax for declaring a template function?

Select the correct answer

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 1. Chapter 2
some-alt