TITLE: Reducing executable code size with templates


[ This example adapted from "C++ Gotcahs," tutorial notes
  by Tom Cargill, p. 70 ]


A very simple technique to avoid some of the code "bloat" pointed
out in the previous tips is shown below. The basic idea is to move
common code into a non-template function which usually deals with
the type "void*". 

Then define a template which uses this common function. Typically
the template can be "inlined". The example below is for the 
checksum() function, but can be easily extended to handle classes
as well.


int checksumAux (const void* p, size_t sz)
{
	const char* cp = (const char*) p;

	int sum = 0;

	for (int i = 0; i< sz; i++)
		sum += cp [i];

	return sum;
}


template <class T>
/* inline */ int checksum (T p)
{
	return checksumAux (p, sizeof (*p));
}
