YouTip LogoYouTip

Cpp Templates

# C++ Templates Templates are the foundation of generic programming, which involves writing code in a way that is independent of any particular type. Templates are blueprints or formulas for creating generic classes or functions. Library containers, like iterators and algorithms, are examples of generic programming that use the concept of templates. Each container has a single definition, for example, **vector**, we can define many different types of vectors like **vector ** or **vector **. You can use templates to define functions and classes. Let's see how to use them. ## Function Templates The general form of a template function definition is shown below: templateret-type func-name(parameter list){// Function body} Here, `type` is a placeholder name for the data type used by the function. This name can be used within the function definition. Here is an example of a function template that returns the maximum of two numbers: ## Example #include#includeusing namespace std; templateinline T const&Max(T const&a, T const&b){return a<b ? b:a; }int main(){int i = 39; int j = 20; cout<<"Max(i, j): "<<Max(i, j)<<endl; double f1 = 13.5; double f2 = 20.7; cout<<"Max(f1, f2): "<<Max(f1, f2)<<endl; string s1 = "Hello"; string s2 = "World"; cout<<"Max(s1, s2): "<<Max(s1, s2)<<endl; return 0; } When the above code is compiled and executed, it produces the following result: Max(i, j): 39Max(f1, f2): 20.7Max(s1, s2): World ## Class Templates Just as we define function templates, we can also define class templates. The general form of a generic class declaration is shown below: template class class-name {...} Here, **type** is the placeholder type name, which can be specified when the class is instantiated. You can define multiple generic data types by using a comma-separated list. The
← Lua Error HandlingPostgresql Limit β†’