I have a class, say, “CDownloader”, that reads some XML data and provides access by node names. It features some getter functions, something like this:
BOOL CDownloader::getInteger ( const CString &name, int *Value );
BOOL CDownloader::getImage ( const CString &name, BOOL NeedCache, CImage *Image );
BOOL CDownloader::getFont ( const CString &name, CFont *Font );
I cannot change CDownloader class. Instead I would like to write some functions, that downloads items by using a bool flag, not an actual name. Something like this:
BOOL DownloadFont( const CDownloader &Loader, bool Flag, CFont *Font )
{
if (Flag) {
// first try the "name_1"
if ( Loader.getFont("name_1", Font) ) return TRUE;
}
// if "name_1" fails or disabled by flag, try "name_2"
return Loader.getFont("name_2", Font);
}
I can write Download(Font|Integer|Image) functions separatly, but this will result in code duplication. My idea is to write a template, but I am still at a loss: how can I determine what method should I call from CDownloader class? To specialize template for each data type means to stuck into code duplication again. To pass getter funciton as a “pointer-to-function” parameter? But the getter signatures differ in CDownloader…
Summing it up, the question is: is it possible to write a generic wrapper around CDownloader or do I have to duplicate code for each “get***” function? Thanks in advance!
As long as you have three differently named functions and need to pick one depending on the type, at some point you have to have either an overload or some traits class to picks the right one. I don’t think there’s a way around that. However, since the call to one of these function is the only thing that needs this, if there is more code to these
DownloadXXX()functions than you showed us, then it might still make sense.Here’s a sketch of what you might do using the overload alternative. First you need three overloads of the same function each calling one of the three different functions. The additional
BOOLparameter for one of the functions somewhat wreaks havoc with the genericity, but I got around that by having all functions accept thatBOOL, but two of them ignoring it:Now you can go and write that generic function. You need to decide what to do about that
BOOL, though:However, as you can see, this is really only worth the hassle if that
Downloadfunction is a lot more complicated than in your sample code. Otherwise the added complexity easily outweighs the gains that the increased genericity brings.