Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove/Insert code at compile time without duplication in C++

Tags:

c++

templates

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?

like image 801
Samaursa Avatar asked Jul 21 '26 05:07

Samaursa


2 Answers

If the values in the policy are const, the compiler can optimize the generate code because it can see which if is always true or always false.

like image 174
PRouleau Avatar answered Jul 22 '26 19:07

PRouleau


You can always change code

   if (T_Policy::trackElements) { /* some code here */ }

into

template <bool b>
void trackElementPhase() {
  /* some code here */
}

template <>
void trackElementPhase<false>() {} // empty body

 ... later in the code

     trackElementPhase<T_Policy::track_elements>();

Of course T_Policy::track_elements has to be compile time constant for this.

However, I wouldn't bother. The compiler is likely clever enough to optimize out code in

   if (T_Policy::trackElements) { /* some code here */ }

if the condition is compile time constant.

like image 34
jpalecek Avatar answered Jul 22 '26 21:07

jpalecek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!