Category Archives: Advanced c++

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
{
public:

// 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?
if(bErr)
{
// 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_; }

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

private:
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

 

   Mock3rdPartyCall(loggingFunctor);

 

 

   std::cout

 

      &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?