Зміст курсу
C++ Templates
C++ Templates
Creating Your First Template in C++
Let's see what is happening when we specify different types for the template. For this we will use typeid().name()
, it simply shows the data type of the variable. Look at the example below:
main
#include <iostream> int main() { int x = 5; std::cout << typeid(x).name(); }
Note
The code snippet above will just display in console
i
, symbolizing thatx
is anint
.
Let's create a template using <typename Type>
and pass Type
as a parameter to the function instead of specifying a specific variable.
main
#include <iostream> template<typename Type> void check_type() { std::cout << typeid(Type).name() << std::endl; } int main() { // Try to change `int` to different type check_type<int>(); }
As you can see, when you call the template function and specify a type within the brackets, the typename
parameter receives that type. The name of the template parameter essentially becomes an alias for that type.
Swipe to start coding
- Turn the
swap
function into a template function:- define template using the
template
keyword; - add the list of template parameters;
- add one parameter for the template.
- define template using the
- Change all types (
int
) to thetypename
from the template parameter. - Call the template function and pass
char
as the type, swapping two variables in themain
function.
Рішення
solution
Дякуємо за ваш відгук!
Creating Your First Template in C++
Let's see what is happening when we specify different types for the template. For this we will use typeid().name()
, it simply shows the data type of the variable. Look at the example below:
main
#include <iostream> int main() { int x = 5; std::cout << typeid(x).name(); }
Note
The code snippet above will just display in console
i
, symbolizing thatx
is anint
.
Let's create a template using <typename Type>
and pass Type
as a parameter to the function instead of specifying a specific variable.
main
#include <iostream> template<typename Type> void check_type() { std::cout << typeid(Type).name() << std::endl; } int main() { // Try to change `int` to different type check_type<int>(); }
As you can see, when you call the template function and specify a type within the brackets, the typename
parameter receives that type. The name of the template parameter essentially becomes an alias for that type.
Swipe to start coding
- Turn the
swap
function into a template function:- define template using the
template
keyword; - add the list of template parameters;
- add one parameter for the template.
- define template using the
- Change all types (
int
) to thetypename
from the template parameter. - Call the template function and pass
char
as the type, swapping two variables in themain
function.
Рішення
solution
Дякуємо за ваш відгук!