Hi,
Can anyone explain me when do we use Template classes ?
Thanks
Printable View
Hi,
Can anyone explain me when do we use Template classes ?
Thanks
There are several cases where you can use template classes/methods :
- templates can be used for static polymorphism.
- templates can be used when an algorithm works on different types that meet certain criteria.
- templates can be used for meta programming to optimize algorithms at compile time instead of runtime (template meta programming)
Since you're apparently starting with templates, you can primarily think of using templates whenever you need to construct a class or an algorithm that works for any kind of data type: primitive types like int and double and/or user-defined ones. (This is basically a generalization of GNiewerth's second item.)
Once you get over it you'll probably be interested on doing some fancy things. And then there's a whole new story that would relate to the other items mentioned by GNiewerth. ;)
I'm using templates for a "super" class in a object-oriented DBMS. (Sounds more complex than it is)
I can easily create different datatypes in the DBMS by creating a class that inherit the superclass like:
So to sum it up, for me template classes are about code re-use. Why bother rewriting a class for another datatype when you can write "template<class T>" on top and replace the otherwise fixed datatypes with the T varable datatype. Then the class can be used for all datatypes/classes - pretty neat!Code:class stringProperty : property<string>
{
// some stringProperty methods etc..
}
Its also worth noting that templates classes can be made using a non-type template parameter.
Heres an example from my latest project.
Code:template < uint N >
class Sequence
{
private:
IntVec sequence_;
Sequence( const Sequence& );
Sequence& operator =( const Sequence& );
public:
Sequence()
{
sequence_.reserve( N );
for ( int i = 1; i <= N; ++i )
{
sequence_.push_back( i );
}
Shuffle();
}
const IntVec& GetSequence() const
{
return sequence_;
}
staticvoid Randomize( uint def = 0 )
{
if ( def == 0 )
def = static_cast<uint>( std::time( 0 ) );
std::srand( def );
}
void Shuffle()
{
std::random_shuffle( sequence_.begin(), sequence_.end() );
}
};
Hmmm seems msvc9 has awful cut/paste trouble. Gives fancy syntax colouring but cant preserve indentation grrr