How to limit the data types that can be used for instantiating a template class?
In C++ there is no standard mechanism to limit the data types that a template can be created with. For example,
template < class T>
class ATemplate
{
};
The above class (ATemplate) can be instantiated with any data type. So ‘T’ can be any data type (eg. basic data types, structures and classes). But what if you want to accept only selected data types? For example a template which only supports char, int and double. C++ doesn’t have a standard method to do it. But Microsoft have put some effort in .NET Generics (something like a C++ template) to limit the data types which can be supported. Even though C++ doesn’t support it directly it is possible to get the data types limited in C++ by making a small trick. Let us see an example.
template < class T >
class MyTemplate
{
T m_x;
void AllowThisType( int& obj ){}
void AllowThisType( char& obj ){}
void AllowThisType( double& obj ){}
public:
MyTemplate()
{
T tmp;
AllowThisType( tmp );
}
void SetX( T val )
{
m_x = val;
}
void print()
{
std::cout<< m_x<< std::endl;
}
};
int main()
{
MyTemplate < int > objint;
MyTemplate < char > objchar;
MyTemplate < double > objdouble;
MyTemplate < float > objfloat; //<< Error when you create this
}
How do the above program limit the data types that can be used for creating a template class object?
From the constructor of class MyTemplate an overloaded function AllowThisType is called. This function is having 3 different overloads. An integer reference, character reference and a double reference. So when you make object with int, char or double there is an appropriate AllowThisType method that compiler can find and match. But when you create an object with any other data type compiler cannot find a matching AllowThisType overload and hence the compilation fails. Let us see an example.
MyTemplate < float > objfloat;
When you make an object of MyTemplate with T as float compiler will look for an AllowThisType( float& ). Since we did not write an overload like AllowThisType( float& ) the compilation fails. So it is clear that the data types which can be given are limited here. Whenever an addiditional type needs to be supported a new AllowThisType overload must be added with the newly supporting data type.
Showing posts with label liminting template data types. Show all posts
Showing posts with label liminting template data types. Show all posts
Friday, January 18, 2008
Subscribe to:
Comments (Atom)