5.4 Templates-2
5.4 Templates-2
Class Template
Class Template
TemplateParamDeclaration: placeholder
class typeIdentifier
typename variableIdentifier
Instantiating a Class Template
int main()
{
MyClass<int> ob;
ob.setValue(6);
fun(ob);
Output:
return 0; Function called
} 6
typename Keyword
"typename" is a keyword in the C++ programming language used when
writing templates. It is used for specifying that a dependent name in a template
definition or declaration is a type. In the original C++ compilers before the first ISO
standard was completed, the typename keyword was not part of the C++
language and Bjarne Stroustrup used the class keyword for template arguments
instead. While typename is now the preferred keyword, older source code may
still use the class keyword instead.
typename: Example
Define a generic function that returns the greater of its two arguments
• Generic classes are those which describe the functionality without being
bound to any data type. These classes can be used to generate definitions
of classes which are bound to a particular data type. A good example is an
Array class. Functionality of array class will be the same irrespective of
whether the array members are int, float or string.
• Generic functions are similarly those which describe the algorithm without
specifying a particular data type.
• In C++ generic classes and functions are implemented using templates.
The Power of Templates.