In: Computer Science
C++
Often times a user has more than one account at the bank and managers have asked to view the account with the largest balance first. We already have a handy utility function that is used for finding the maximum of two ints.
int max(int a, int b) {
if (b > a) {
return b;
} else {
return a;
}
}
How can we make a generic version? As a first step lets start by using pass by reference, since that will be more efficient when dealing with objects.
int &max(int &a, int &b) {
if (b > a) {
return b;
} else {
return a;
}
}
For this problem create a generic version of the pass by reference max function above. Put it in a new header file called util.h, the purpose of the header is to have a collection of generic utility functions that can be used in many different places.
The function you write needs to be generic (not hard coded to only work with Account), but you should test that it does work with Account. You can test it in main() or in a unit test.
Hey mate, to make a generic version of above function we can use Templates in C++.Template is a simple and yet very powerful tool in C++. The simple idea is to pass data type as a parameter so that we don’t need to write the same code for different data types.
Let's see how to declare a template function -
A function template starts with the keyword template followed by template parameter/s inside < > which is followed by function declaration.
template <typename T>
T someFunction(T arg)
{
// function body
}
C++ adds two new keywords to support templates: ‘template’ and ‘typename’. The second keyword can always be replaced by keyword ‘class’.
In the above code, T is a template argument that accepts different data types (i.e. int, char, float, etc.) and then performs the operation defined in the function body.
When, an argument of a data type is passed to
someFunction( )
, compiler generates a new version of
someFunction()
for the given data type.
for example-
Generic version of pass by reference max() function with testing code -
#include <iostream>
using namespace std;
template <typename T>
T max(T &a, T &b)
{
if (b > a) {
return b;
}
else {
return a;
}
}
int main()
{
float account1=230000; // balance in account 1
float account2=156200; // balance in account 2
cout<< max<float>(account1, account2); // print maximum account balance
return 0;
}
Output -
230000