What are C++ Function Templates?

Generic programming in c++

Cyber Stoat
2 min readOct 31, 2022
(png generated by carbon.now.sh)

According to learn.microsoft

Templates are the basis for Generic programming in C++

Not the exact explanation you are looking for?, okay here is my understanding:
Say for example you are trying to sort users in your application based on their user ID which is int type, so now you write a function to sort them and grab a coffee , and then the product owner asks you to sort their users based on the dues they have to pay which is now in double type, later that day he calls you again (what an a**) and asks you to sort them based on their names in alphabetical order…. before you cry yourself to re write the same code again and again you reach out to google asking for a way to reuse the same code for different generic data types(int,float,double,char…) and for some god knows what reason you end up here reading this blog and find out that's what c++ templates exactly does.
You write one template or say blueprint of your code and re use it for different data types

How that works ? (will write that in some other story)

Okay relax I wont show some sorting code in “this” post lets see how to swap two int types instead:

Now if you run this it works fine but then if you pass something like a double to that swap function you will be greeted with a compilation error like :

So we create a template for swap like this:

See how we are able to swap both int and double types using same function call this is how we generic programming is done in c++.
Now a bit of explanation about how to code a template function here

line 3 in above snippet declares that we are writing a template function and the typename T is what holds all the data type , yes it basically acts as a placeholder for your data type , aka when you pass int T is int and when you pass double T is double and now see rest of the swap function, and its arguments as swap(T &a, T &b) in here T changes with the data type that it gets from the function call (in the given example T is int when swap(a,b) is called and T is double when swap(c,d) is called.)

Not just one typename you can use any number of generic types you wqant like this:

template <typename T1, typename T2>

I will leave the usecases for multiple typenames your imagination.
Be back with class templates in my next post, stay awesome.

--

--

Cyber Stoat
Cyber Stoat

Written by Cyber Stoat

Computer Science graduate who codes,eats,sleeps and repeats.

No responses yet