Template use cases

Template use cases

Templates are instantiated at compile time, thus involves static binding. If you’re using inheritance and ploymorphism, the dynamic binding is done at run time.Thus the “effect” is not the same.

1. Using template to write generic Swap function:

template<class T>  void swapRef(T& obj1, T& obj2) {

T temp = obj1;

obj1 = obj2;

obj2 = temp;


2. Templates used for implementation of  a functor :

class LoggingFunctor

// Constructor allows user defined output stream
LoggingFunctor(std::ostream & os) :
os_(os), nErrCnt_(0), nLogCnt_(0) {}

// Overload for std::string
void operator()(std::string const & s, bool bErr)
// Hand off to overload for char const *
(*this)(s.c_str(), bErr);

// The main logging funcion
void operator()(char const * szMsg, bool bErr)
// Count log item
++ nLogCnt_;

// Display date & time
time_t t = time(0);
char tbuf[80];
strftime (tbuf,80,”%x %X “,localtime(&t));
os_ << tbuf;

// If error message?
// Count error and display error prefix
++ nErrCnt_;
os_ << “ERROR: “;

// NOw log it
os_ << szMsg << std::endl;

// Accessors to the log and error count
int GetErrCnt() const { return nErrCnt_; }
int GetLogCnt() const { return nLogCnt_; }

// Non-copyable semantics to prevent accidental copy or assignment
LoggingFunctor(LoggingFunctor const &);
LoggingFunctor operator=(LoggingFunctor const &);

std::ostream & os_;
int nErrCnt_;
int nLogCnt_;
template <typename LoggingFunctorT>
void Mock3rdPartyCall(LoggingFunctorT & logger)
for(int i = 0 ; i < 25; ++i)
// Build a log message
std::stringstream ss;
ss << “Log entry ” << i;

// Log it, treat every 3rd iteration as an error
logger(ss.str(), i%3 == 0);

int main()




   // Log to stdout for this example


   LoggingFunctor loggingFunctor(std::cout);



   // Call the mock 3rd party function







      &amp;lt;&amp;lt; std::endl


      &amp;lt;&amp;lt; loggingFunctor.GetLogCnt() &amp;lt;&amp;lt; &amp;quot; items logged, &amp;quot;


      &amp;lt;&amp;lt; loggingFunctor.GetErrCnt() &amp;lt;&amp;lt; &amp;quot; of which were errors.&amp;quot; &amp;lt;&amp;lt; std::endl;



3. Usage of template in Observer design pattern :

Observer design pattern


Why can’t I separate the definition of my templates class from its declaration and put it inside a .cpp file?



Resolving technical problems:

Solve your technical problems instantly

We provide Remote Technical Support from Monday to Sunday, 7:00PM to 1:00 AM

Mail your problem details at writeulearn@gmail.com along with your mobile numberand we will give you a call for further details. We usually attend your problems within 60 minutes and solve it in maximum 2 days.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.