Code Newbie
News     Forums     Search     Members     Sign Up    

My Code Newbie
Username

Password

Articles/Snippets
ASP Classic
ASP.NET
C
C#
C++
HTML / CSS
Java
Javascript
Linux / BSD
Perl
PHP
Python
Ruby
SQL
VB 6
VB.NET

C.N. Friends
  Planet Rome

Link to Us!
Code Newbie
  Code Newbie
    cpp
  » Template Specialization
      by Scott Deming
 Page 2 of 3 
< Previous     Next >

(Login to remove green text ads)
A useful template function
The following template free-function is useful for displaying some helpful type information such as sizeof, min, and max. This is essential information when porting a 32 bit application to 64 bit.

templated print() function
Code:
template<typename T> void print(T zero, const char* name) { cout << name << ": s(" << sizeof(T) << ") [" << setw(20) << numeric_limits<T>::min() << " : " << setw(20) << numeric_limits<T>::max() << "]" << endl; }
There are of course some limitations to this, and so we will have to specialize. Since we are looking for numeric values here and the ostream object will be using its default operator<< overload, we will have to rewrite how it treats char and unsigned char data types so they are displayes as numbers and the character representations of those numbers. With this in mind, we have the following two specialized functions:

specialized print() function for char
Code:
template<> void print<char>(char zero, const char* name) { cout << name << ": s(" << sizeof(char) << ") [" << setw(20) << static_cast<int>(numeric_limits<char>::min()) << " : " << setw(20) << static_cast<int>(numeric_limits<char>::max()) << "]" << endl; }
specialized print() function for unsigned char
Code:
typedef unsigned char UCHAR; typedef unsigned int UINT; template<> void print<UCHAR>(UCHAR zero, const char* name) { cout << name << ": s(" << sizeof(UCHAR) << ") [" << setw(20) << static_cast<UINT>(numeric_limits<UCHAR>::min()) << " : " << setw(20) << static_cast<UINT>(numeric_limits<UCHAR>::max()) << "]" << endl; }
Prior to being passed into the cout stream, we have to cast these as int (for char) and unsigned int (for unsigned char) so the streams class will display the correct values.




 
 Page 2 of 3 
< Previous     Next >

Rate This Article
1 2 3 4 5 6 7 8 9 10





Copyright © 2000-2006, Milano Interactive
Web Hosting provided by Portal 360 Web Hosting
Open Circle