Template Specialization in C++

This is one of the new things which I learnt this week. In this blog post we will talk about Template Specialization in C++.

So I am really enjoying coding in Cpp and playing with the core internals. The power which comes which system level languages are amazing. You can actually go and see closely how exactly things work! No abstractions!

Coming back to the topic.

Templates in C++ gives us the freedom to write a logic which can run on any data type, unlike functions. If you are coming from a python background then you can draw an analogy of pythonic functions and templates in cpp.

#include <typeinfo>

template <typename T>
T getType(T x)
{
       cout << "The type of variable is" << typeid(x).name();
       return typeid(x).name();
}

Template Specialization –¬†

So basically want a template function to do a specific task for a particular data type.

// specialized function
template<>
char getType<char>(char x)
{
	cout << "Specialized template\n";
	return 1;
}

I hope that the above few lines of code is good for you when you(‘Vipul’) read this blog in future.

However I am quoting some information from geeksforgeeks.

What if we want a different code for a particular data type? Consider a big project that needs a function sort() for arrays of many different data types. Let Quick Sort be used for all data types except char. In case of char, total possible values are 256 and counting sort may be a better option. Is it possible to use different code only when sort() is called for char data type?
It is possible in C++ to get a special behavior for a particular data type. This is called template specialization.

This is another interesting bug which I found on stackoverflow about Template Specialization in different namespaces bug in g++.

Some reference links –

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s