I have a template class that is taking in a couple of types. One type is there just to determine policies. That class determines how a function may work in certain cases.
Let’s say this is one of the function:
/* this code is part of a class */
template <typename T, typename T_Policy> // Not important but just showing the template parameters of the class
void Allocate(unsigned int numElements)
{
// Some code here
while (someCondition) // Other functions don't have the loop, this is just an example
{
// Some code here
if (T_Policy::trackElements) { /* some code here */ }
if (T_Policy::verbose) { /* some code here */ }
if (T_Policy::customManager) { /* some code here */ }
/* and a few other policies */
}
// Some more code here
}
I would like the lines of code that are using the policies to be compiled out instead of relying on if statements. One obvious way is to put the while loop in overloaded functions each taking a dummy object with a specific policy type. But that means a lot of code duplication. Similar approaches with template specialization will result in code duplication as well.
Is there a way to compile out the code without code duplication?
You can always change code
into
Of course
T_Policy::track_elementshas to be compile time constant for this.However, I wouldn’t bother. The compiler is likely clever enough to optimize out code in
if the condition is compile time constant.