Click here to Skip to main content
15,881,882 members
Articles / Programming Languages / C++
Tip/Trick

C++ Numeric Limits and Template Specialization

Rate me:
Please Sign up or sign in to vote.
4.00/5 (1 vote)
3 Mar 2014CPOL2 min read 21.7K   3   6
C++ Numeric Limits and Template Specialization

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...

C++
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...

C++
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.

C++
myData<int> obj;

obj.setData(5);
obj.printData();

This will generate the following output:

MC++
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:

C++
std::cout<<"Maximum Value of integer can take is ="<<std::numeric_limits<int>::max()<<std::endl;

And it will print the following...

C++
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...

C++
 class soldier {
    //...
    int _age;
    //... 
}    

We can't do this... your code will not compile.

C++
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:

C++
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...

C++
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...

C++
 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:

C++
std::cout<<"Maximum age for a soldier is "<<std::numeric_limits<soldier>::max()<<"\n";

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer Yahoo
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
Suggestionstd::numeric_limits must not be extended Pin
.:floyd:.4-Mar-14 10:27
.:floyd:.4-Mar-14 10:27 
The namespace std is protected, and may only contain what is specified in the C++ Standard. C++ client code must not place anything into namespace std. What you suggest is not valid C++.

You might also want to add a note that std::numeric_limits is a strange animal, and its semantics are confusing, to say the least. While std::numeric_limits<int>::min() returns the smallest negative number representable by the (signed) int type, std::numeric_limits<float>::min() returns the smallest positive number, representable by the (signed) float type.

.f
GeneralRe: std::numeric_limits must not be extended Pin
vikrantc13554-Mar-14 14:41
vikrantc13554-Mar-14 14:41 
GeneralRe: std::numeric_limits must not be extended Pin
.:floyd:.4-Mar-14 15:46
.:floyd:.4-Mar-14 15:46 
GeneralRe: std::numeric_limits must not be extended Pin
vikrantc13554-Mar-14 16:04
vikrantc13554-Mar-14 16:04 
GeneralRe: std::numeric_limits must not be extended Pin
.:floyd:.5-Mar-14 4:49
.:floyd:.5-Mar-14 4:49 
GeneralRe: std::numeric_limits must not be extended Pin
vikrantc13555-Mar-14 7:42
vikrantc13555-Mar-14 7:42 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.