Introduction
The purpose of this article is to explain the usage of Template Specialization with an example. It requires users to have some basic understanding on C++ programming & templates.
Template
C++ allows users to write generalized code using templates. What it means is that if you have a class like this...
class myData {
int i;
public:
void printData() { std::cout<<i<<"\n"; return; }
void setData(const int &value) { i = value; return; }
};
You can generalize it in the following manner...
template <class T> class myData {
T i;
public:
void printData() { std::cout<<i<<"\n"; return; }
void setData(const T &value) { i = value; return; }
};
and then use it with your desired type on a need basis.
myData<int> obj;
obj.setData(5);
obj.printData();
This will generate the following output:
5
Numeric Limits
Numeric Limits is another C++ feature which is not known to everyone, and can be useful in many cases. Defined in "limits" , and part of "std" namespace, it provides you an Interface to find various limits of different types.
What it means is that if you want to know what is the maximum value an int
can support... you can do this:
std::cout<<"Maximum Value of integer can take is ="<<std::numeric_limits<int>::max()<<std::endl;
And it will print the following...
Maximum Value of integer can take is = 2147483647
Interface is quite powerful... and has most of the limits and other stuff defined. IT can also tell you if one type is signed or not. I recommend having a look at the "limits" class for more insight.
Template Specialization for Numeric Type
Problem with numeric_limit
is that it works only with basic type. If it is user defined type.. then we cannot use numeric_type
for them. For example, if I have a class like this...
class soldier {
int _age;
}
We can't do this... your code will not compile.
std::numeric_limits<soldier>::max();
Here, we can use Template Specialization to define limits for us. C++ allows you to define special cases for your templates... so if we take our first example (i.e. myData
), we can specialize it for one type (let's say bool
) in the following way:
template <> class myData<bool> {
bool i;
public:
void printData() { i?std::cout<<"true\n":std::cout<<"false\n"; return; }
void setData(const bool &value) { i = value; return; }
};
And now, we can use it this way...
myData<bool> flag;
flag.setData(true);
flag.printData();
I am skipping the output part.. as it is quite obvious.
Now we can use template specialization to define max for soldier class. Let's say definition of max is "Maximum Age" and let's also take some value (say 50).
What we need to do it specialize numeric_limits
class to support our type. Something like the following...
namespace std {
template<> class numeric_limits<soldier> {
public:
static int max() {return 50;};
};
}
Now you can use numeric_limits
for your type ... in the following way:
std::cout<<"Maximum age for a soldier is "<<std::numeric_limits<soldier>::max()<<"\n";