Basic Syntax of Templates in C++
Veeg om het menu te tonen
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 occurs when you try to call it as if it were a regular function. This happens because it is no longer just a simple function. At this point, the template parameter specified inside the angle brackets after the template keyword becomes essential.
main.cpp
12345678910111213#include <iostream> // This essentioally creates an alias for a type you will use template<typename Name> // In this 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 // You need to specify any type inside the brackets MyFirstTemplate<void>(); // This tells the template to use void as the type for Name }
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.
Bedankt voor je feedback!
Vraag AI
Vraag AI
Vraag wat u wilt of probeer een van de voorgestelde vragen om onze chat te starten.