I am looking for a way to identify primitives types in a template class definition.
I mean, having this class :
template
class A{
void
The following example (first posted in comp.lang.c++.moderated) illustrates using partial specialisation to print things differently depending on whether or not they are built-in types.
// some template stuff
//--------------------
#include
#include
#include
using namespace std;
// test for numeric types
//-------------------------
template struct IsNum {
enum { Yes = 0, No = 1 };
};
template <> struct IsNum {
enum { Yes = 1, No = 0 };
};
template <> struct IsNum {
enum { Yes = 1, No = 0 };
};
// add more IsNum types as required
// template with specialisation for collections and numeric types
//---------------------------------------------------------------
template struct Printer {
void Print( const T & t ) {
typename T::const_iterator it = t.begin();
while( it != t.end() ) {
cout << *it << " ";
++it;
}
cout << endl;
}
};
template struct Printer {
void Print( const T & t ) {
cout << t << endl;
}
};
// print function instantiates printer depoending on whether or
// not we are trying to print numeric type
//-------------------------------------------------------------
template void MyPrint( const T & t ) {
Printer ::Yes> p;
p.Print( t );
}
// some test types
//----------------
typedef std::vector Vec;
typedef std::list List;
// test it all
//------------
int main() {
Vec x;
x.push_back( 1 );
x.push_back( 2 );
MyPrint( x ); // prints 1 2
List y;
y.push_back( 3 );
y.push_back( 4 );
MyPrint( y ); // prints 3 4
int z = 42;
MyPrint( z ); // prints 42
return 0;
}