![cppcolors | Embarcadero RAD Studio Delphi C++Builder Blogs](https://i0.wp.com/blogs.embarcadero.com/wp-content/uploads/2020/08/cpp_colors.jpg?resize=1140%2C628&ssl=1)
Table of Contents
C++ Templates : Blueprints for Generic Classes and Functions
C++ Templates are a powerful feature within the C++ language that extends your capabilities within C++. Templates are a foundation of generic programming that lets you reuse your source code if you have multiple data types that you wish to pass instead of function overloading or rewrites.
Why use templates?
- To avoid repeating code.
- Not bound to certain types
- Code can be easier to look at
- Increased flexibility
- Better than macros
- We can’t do much without them
Function Templates
Function templates are special functions that can operate with generic types allowing you to create a function whose functionality can be adapted to more than one type without repeating the code for each type.
Syntax:
template <class identifier>function_declaration;
template <typename identifier> function_declaration;
template <typename T>
T FindMin (T a, T b)
{
T result;
result = (a > b) ? a : b;
return (result);
}
- T is a template argument and class is a keyword.
- We can also use keyword typename instead of class
- When an argument is passed to FindMin(), the compiler generates a new version of FindMin() to work on the argument of that type.
Class Templates
A class template is a common class that can represent various similar classes operating on data of different types.
Syntax:
template <class T1,class T2, ...>
class classname
{
attributes;
methods;
};
Implementing C++ Templates
Here are the code snippets I use the webinar:
A basic function template where I define a template that uses a single typename mary that can be replaced by the data type that I want to use later. I am calling myMax function to see which is larger between the integers and characters.
template<typename mary>
mary myMax (mary x, mary y)
{
return (x > y) ? x: y;
}
int _tmain (int argc, _TCHAR* argv[])
{
cout << myMax<int>(5,10) << endl;
cout << myMax<char>(‘m’, ‘k’) << endl;
system(“pause”); //Only works on Windows and is a bit of a dirty trick
return 0;
}
Here is another example of a function template that contains two types in my standard template format. Check out the video for more on this.
template <typename T1, typename T2>
T2 product (T1 x, T2 y)
{
return x * y;
}
int _tmain(int argc, _TCHAR* argc[])
{
cout << product (3, 4.8) << endl;
cout << product (4, 5.5) << endl;
system (“pause”); //Only works on Windows and is a bit of a dirty trick
return 0;
}
Like function templates, class templates (below) can be a useful solution to classes that need to define an “independent” or variable data type.
template <class T>
class Programmer{
T first, last;
public:
Programmer (T a, T b){
first = a;
last = b;
}
T myMax ();
};
template <class T>
T Programmer<T>::myMax(){
return (first > last ? first : last);
}
int _tmain (int argc, _TCHAR* argv[])
{
Programmer<int>progobj (30, 59); //Between class and object, add the data type
cout << progobj.myMax();
system(“pause”); //Only works on Windows and is a bit of a dirty trick
return 0;
}
Watch the webinar replay here:
{“video”:”https://www.youtube.com/watch?v=Fpm6-Ul4HcE&feature=youtu.be”,”width”:”400″,”height”:”225″}
During the Q&A, I was asked a few questions that I wanted to make sure had received responses. Keep scrolling to see some of those responses to the questions.
Can you not explicitly instantiate your template as you did in the function templates example? IE: Do you have to put <int> or <char> before (5, 10) and (‘m’,‘k’)?
No you don’t have to explicitly instantiate; When the compiler sees this instance of the function template, for example, myMax (5, 10) in your main function, it generates the function myMax (int, int). Don’t believe me? Test it out yourself. Open a console application in C++Builder and write out the function myMax code provided above, but don’t include <int> after myMax.
You mentioned that your application code can be larger when you use templates, how does that affect…(fill in with your question)
This can seem counterintuitive when thinking about how less source code being written would see to increase your compiled code. It isn’t really the template itself that bloats your application. It is the misuse/handling of templated code that can cause larger applications. To gain a greater understanding of function and class templates, I would recommend spending some time with the Standard Template Library (STL).
I missed the resources page, can you please provide the titles for me?
- The Design and Evolution of C++ by Bjarne Stroustrup
- C++ Templates: The Complete Guide (2nd Edition) by David David Vandevoorde, Nicolai M. Josuttis, Douglas Gregor
- The C++ Standard Library: A Tutorial and Reference (2nd Edition) by Nicolai M. Josuttis
- Modern C++ Design by Andrei Alexandrescu
- Using the C++ Standard Template Libraries by Igor Horton
- CPP Reference
Design. Code. Compile. Deploy.
Start Free Trial Upgrade Today
Free Delphi Community Edition Free C++Builder Community Edition