Зміст курсу
C++ Templates
C++ Templates
Basic 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.
main
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.
template
// 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
#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
#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.
Дякуємо за ваш відгук!