+ 3
What's the work of template in C++
I saw a program using "templates" and I don't know what templates are. Can anyone tell me what templates are?
2 odpowiedzi
+ 3
Templates are powerful features of C++ which allows you to write generic programs and create a single function or a class to work with different
data types using templates. The concept of templates can be used in two different ways:
1. Function Templates
A function template starts with the keyword template followed by template parameter/s
inside < > which is followed by function declaration.
template <class T>
T someFunction(T arg)
{
... .. ...
}
In the above code, T is a template argument that accepts different data types
(int, float), and class is a keyword.
Please see code at https://code.sololearn.com/csuBln5Bonmg/#cpp
•Class Templates
Like function templates, you can also create class templates for generic class operations that are same for all classes, only the data types used are different.
How to declare a class template?
template <class T>
class className
{
... .. ...
public:
T var;
T foo(T arg);
... .. ...
};
In the above declaration, T is the template argument which is a placeholder for
the data type used.
Please go through code at https://code.sololearn.com/cG3QotFhSMI4/#cpp
+ 1
thank you