Assume we have a function
template< typename A, typename B, typename C >
void function(vector<A>& keyContainer, int a, int b, int c, boost::function<bool(B&)> selector, C* objPointer = NULL)
{
BOOST_FOREACH(const A& key, keyContainer)
{
B* pVal = someGetObjFunction(objPointer, key);
if(pVal)
{
if(selector && selector(*pVal))
{
pVal->someOtherFunction(1,2,3);
}
//some more code
}
}
}
This looks bad because it will always enter the
if(selector && selector(*pVal))
even when it is NULL, an obvious approach to fix this would be :
template< typename A, typename B, typename C >
void function(vector<A>& keyContainer, int a, int b, int c, boost::function<bool(B&)> selector, C* objPointer = NULL)
{
if(selector)
{
BOOST_FOREACH(const A& key, keyContainer)
{
B* pVal = someGetObjFunction(objPointer, key);
if(pVal)
{
if(selector(*pVal))
{
pVal->someOtherFunction(1,2,3);
}
//some more code
}
}
}
else
{
BOOST_FOREACH(const A& key, keyContainer)
{
B* pVal = someGetObjFunction(objPointer, key);
if(pVal)
{
pVal->someOtherFunction(1,2,3);
//some more code
}
}
}
}
But this resulted in a lot of code duplication, another approach would be making a specialization for the case when the function is NULL but wouldnt that be almost identical as the example above? Is there another way of doing that without duplicating all the code ?