Most C++ programmers stay away from C++ templates due to their perplexed nature. The excuses against templates:
Hard to learn and adapt.
Compiler errors are vague, and very long.
Not worth the effort.
Admitted that templates are slightly hard to learn, understand, and adapt. Nevertheless, the advantages we gain from using templates would outweigh the negatives. There is a lot more than generic functions or classes that can be wrapped around templates. I would explicate them.
While C++ templates and STL (Standard Template Library) are siblings, technically. In this article, I would only cover templates at the core level. Next parts of this series would cover more advanced and interesting stuff around templates, and some know-how about STL.
- Pointers, References and Arrays with Templates
- Multiple Types with Function Templates
- Function Template - Template Function
- Explicit Template Argument Specification
- Default Arguments with Function Templates
- Multiple Types with Class Templates
- Non-type Template Arguments
- Template Class as Argument to Class Template
- Default Template Arguments with Class Templates
- Class' Methods as Function Templates
The Syntax Drama
As you probably know, template largely uses the angle brackets: The less than ( < ) and the greater than ( > ) operators. For templates, they are always used together in this form:
< Content >
Where Content can be:
class T / typename T
A data type, which maps to T
An integral specification
An integral constant/pointer/reference which maps to specification mentioned above.
For point 1 and 2, the symbol T is nothing but some data-type, which can be any data-type - a basic datatype (int, double etc), or a UDT.
Read more: Codeproject
QR: