Basic Syntax of Templates in C++
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.
main.cpp
123456void 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.
template.h
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.
main.cpp
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.
main.cpp
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.
Tack för dina kommentarer!
Fråga AI
Fråga AI
Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal