Changing pointer passed to a function as argument
June 14, 2012
Permutations of list of elements with repeated values
June 14, 2012

Function Templates in C++

What are function templates in C++? Why and how are they used ?

Solution:

Let us write a simple function to compute sum of two integers

    int sum(int a, int b)
    {
        return a+b;
    }

If we want to find the sum of two floats, then above function will not give the desired result. So we have to write another function (C++ allows function overloading, so we can keep the name same)

    float sum(float a, float b)
    {
        return a+b;
    }

Similarly, if we want to compute the sum of two double values, the function will change to

    double sum(double a, double b)
    {
        return a+b;
    }

So we have three functions with same functionality (body of function) and just differ on the parameter type.

There are two basic problems with this approach (overloading functions which have exactly same functionality and just differ on types).

  • Maintainability: Suppose we want to add functionality that when addition of two numbers is performed then log that in a text file. We have to put that logging functionality in all the three places.
  • Addition: If we want to compute sum of two long values (or any other user type) then we have to write separate functions. There will be lot of duplication of code this way.

Next: C Language Solution …

1 Comment

  1. SEO says:

    Great goods from you, man. I’ve understand youir stuff previous to
    and you’re just too fantastic. I really like
    what you’ve acquired here, certainly like what you’re
    stating and the way bby which you are saying
    it. You mwke it enjoyable and you continue to care for to keep
    it sensible. I can not wait to read far more from you.
    That is actually a great website.

Leave a Reply to Anonymous Cancel reply

Your email address will not be published. Required fields are marked *