single
Creating Your First Template in C++
Sveip for å vise menyen
Let's see what is happening when you specify different types for the template. For this you will use typeid().name(), it simply shows the data type of the variable. Look at the example below:
main.cpp
1234567#include <iostream> int main() { int x = 5; std::cout << typeid(x).name(); }
The code snippet above will just display in console i, symbolizing that x is an int.
Let's create a template using <typename Type> and pass Type as a parameter to the function instead of specifying a specific variable.
main.cpp
12345678910111213#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.
You can also use that template parameter inside the function body to declare variables of that exact type.
main.cpp
12345678template<typename Type> void create_variable() { Type value; // Variable of the template type value = Type(); // Default initialization std::cout << value << std::endl; }
Swipe to start coding
- Turn the
swapfunction into a template function:- define template using the
templatekeyword; - add the list of template parameters;
- add one parameter for the template.
- define template using the
- Change all types (
int) to thetypenamefrom the template parameter. - Call the template function and pass
charas the type, swapping two variables in themainfunction.
Løsning
Takk for tilbakemeldingene dine!
single
Spør AI
Spør AI
Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår