≡ Menu

C++ Template Functions Explained with an Example Program

Let us assume that we are in the situation where we need to create a function that calculates the absolute value of a number.

When you have a number that is positive, then absolute value of the number is that same number, but if the number is negative, then the absolute value of the number is that number with sign changed.

So, the function, if you work with int data type would be like this:

int AbsolteValue( int nNumber)
{
  return (nNumber>0)? nNumber:-nNumber;
}

But, what if somebody needs the same function with double data type, instead of int? In that case, you can create a function like the following:

double AbsoluteValue( double dNumber)
{
return (dNumber>0)? dNumber:-dNumber;
}

In the way same, we can keep creating functions reactively to cover: float, long int, long long int, long double and so on.

There could also be a possibility when you don’t want to use the usual data types, but like to use your own custom data type with typedef.

We cannot possibly predict all data types that our function could potentially use. In those situations, “function templates” comes to rescue.

C++ Function Template Syntax

There are two acceptable syntaxes:

template <class TypeName1, class TypeName2, ...>

Or,

template <typename Typename1, typename TypeName2>

Now, the function could be like this:

tempalte<typename T>
T
AbsoluteValue( T tNumber)
{
return (tNumber>0)? tNumber: -tNumber;
}

So, the algorithm does not depend on data type used in code any more. The algorithm is implemented no matter what data type is used.

Now it is time to ask yourself, what do we get and what do we lose with this approach.

Well, we gain from point of generality and we lose from point of speed.

In other words, if you need to create faster solution for one data type, don’t use template.

But, if your goal is to create a function that will not care about data types, you should use templates.

C++ Function Template Example Program

The following example C++ program shows how you can use template.

#include <iostream>

using namespace std;

template<typename T>
T
AbsoluteValue(T tNumber)
{
	return (tNumber>0)? tNumber:-tNumber;
}

int
main( void)
{
	int nNumber1 =  7, 
	    nNumber2 = -7;

	cout<<"Absolute value  of  "
	    <<nNumber1<<"  = "
	    <<AbsoluteValue(nNumber1)<<endl;

	cout<<"Absolute value of "
	    <<nNumber2<<"  = "
	    <<AbsoluteValue(nNumber2)<<endl;

	double dNumber1 = 7.0923, 
	       dNumber2 =-7.0923;

	cout<<"Absolute value of"
	    <<dNumber1<<"  = "
	    <<AbsoluteValue(dNumber1)<<endl;

	cout<<“Absolute value of "
	    <<dNumber2<<"  = "
	    <<AbsoluteValue(dNumber2)<<endl;

	int iExit; cin>>iExit;

	return EXIT_SUCCESS;
}

The output for the above program will be the following:

Absolute value of 7 = 7
Absolute value of -7 = 7
Absolute value of 7.0923 = 7.0923
Absolute value of -7.0923 = 7.0923

As you see in the above example, it has only one function, but it will react to any data types.

As we have seen how we could use template functions to not care about data type, we could use the same trick with C++ classes.

If your C++ supports C11 standard, you can use variadic templates, which has the ability to use more parameters, something like combination of templates and functions of unknown number of arguments.

Additional Exercises to use C++ Template Functions:

  1. Try to find the minimum of two numbers of a unknown, but same data type. (Do the same for minimum of three numbers)
  2. Try to find the maximum of two numbers of a unkonwn, but same data type. (Do the same for maxmimum of three numbers)
  3. Store no more than 100 elements of same, but unknown data type in an array. Try to sort that array.
  4. The input into the function are two 2D(x, y) points of unknown data type. You need to calculate the distance of those two points and convert the result into double as the result of that function.
  5. You are presented with two numbers of unknown data type. Try to find circumference and area of rectangle, constructed with those two numbers as the measurements of rectangle sides.
  6. You are provided with four numbers: x, y, a and b. They have same but unknown data type. You are required to calculate the value of function: f(x,y) = a*x + b*y. The return value of the function is of double data type.
  7. The temperature is given in Celsius but you don’t know the data type. Your task is to convert that data type into double.
Add your comment

If you enjoyed this article, you might also like..

  1. 50 Linux Sysadmin Tutorials
  2. 50 Most Frequently Used Linux Commands (With Examples)
  3. Top 25 Best Linux Performance Monitoring and Debugging Tools
  4. Mommy, I found it! – 15 Practical Linux Find Command Examples
  5. Linux 101 Hacks 2nd Edition eBook Linux 101 Hacks Book

Bash 101 Hacks Book Sed and Awk 101 Hacks Book Nagios Core 3 Book Vim 101 Hacks Book

Comments on this entry are closed.

  • Everaldo February 14, 2014, 2:32 am

    Nice article. Thanks!

  • na February 14, 2014, 3:32 am

    Very good simple illustration! Thank you.

  • Mike February 14, 2014, 4:35 am

    Great article, I enjoyed reading it. Thank you !

  • SeattleC++ February 14, 2014, 11:15 am

    The article incorrectly states, “Well, we gain from point of generality and we lose from point of speed.”

    Since each template instance is separately compiled in C++, the implementation is as fast as if it had been hand-coded for a specific data type. In addition, template functions are inlined by default, so in a small function like absolute value, the template version has no call and return overhead, making it arguably faster than calling a function to perform the absolute value function.

  • Bob February 14, 2014, 12:43 pm

    Great article

  • DuskoKoscica February 14, 2014, 11:55 pm

    THX for nice comments I am very glad that you have found this article usefull. @SeattleC++, I have made this conclusion from text I have read before. Aldo, I have never tested this, so it would be nice to have someone create the test with template and without template. If you create function in the class and if it is small then it is inline by default, and that means that it is left to compiler “to decide” whether is it going to be used like makro or like functinon. The test could be constructed easily and it is something I would like to see results, it would be great contribution to disccusion. Have nice day all of you!

  • DuskoKoscica February 15, 2014, 12:08 am

    Ups, if you implement small function in .h hedder file

  • SeattleC++ February 15, 2014, 9:51 pm

    I have performed *extensive* testing on visual studio, and also examined the generated assembly. Templates are inlined in the release build, and they are very, very fast. You may have read that templates are slow in Java, where they are implemented using casting and just call a generic function. My testing on the gnu C++ compiler has been less extensive, but when built with -O or -O2, templates are usually inlined, and are quite fast when inlined.

  • duskoKoscica February 17, 2014, 2:53 am

    Ok, nice, but what I ment is try to construct the program and show it to people that are less experienced, thet way they will be able to benefit more frome this, that is the way sometimes you need to test you program in practice, and that will help people learn how to practicly use some tricks they could apply in some simmilar sitautions. I don’t say that I don’t trust your seaying, but I think that it would be nicer to have it all, so that all people learn the way ingeeners should think! THX SeatleC++ your comment is great contributino.

  • duskoKoscica February 17, 2014, 6:13 am

    In the situation when you have more cores and you could perform more tasks( Win world treads) and heavy or light proccesses it might be very dificult to test the speed of application because it could lose the procesor and it could go back in some queue, that is the reason way it is tough to say. One more thing, the best practice would be to have template functions in separate files, and when they have been well aproved to use them in other proccesses. Also it is good to know that some optimizations by compiler could be very usefull, and there is a lot of them, so best performance app is sometimes very hard to get.