+ 2
What's the template keyword in CPP & Js?
I want to understand the function of the template keyword in CPP and in js. Thanks in advance.
3 Respostas
+ 8
The template is not for an abstract class, no.
A template class may have objects declared.
In C++, the template keyword allows one to define variables for function and classes that can change their type during compilation. Thus, functions and classes using the following can receive any type of input as arguments or store any type of variable in their members.
Eg -
template<class T>
void myfunc(T arg1)
// You may put anything in arg1; int, char, string, custom class, you name it.
{ /*...*/ }
A template basically declares a seperate class, and substitutes it with the class of the passed argument / variable.
Thus, during compilation, every type will create a separate instance of that function, somewhat like this:
If you use int:
void myfunc(int arg1)
{ /*Modifies code, replacing the class with the class of the arg1 variable, int in this case.*/ }
And in classes, this works the same, but instead, classes are defined separately for each instance.
Eg -
template<class T>
class Myclass
{ public: T mem1,mem2; };
But in classes, you need to specify the type you will be using in the object (eg - Myclass<int> obj1) , since auto detection isn't possible during creation.
0
I understand it similar to an interface in Java or Abstract Class in C++
something you can describe well but will never exists in reality