user19179144
user19179144

Reputation: 309

How to create optimized variations of the same algorithm without too much copy/paste code? (C++)

When I write C++ code for realtime optimised purposes, such as audio or graphics processing, I run into the following problem quite often:

I need several variations of piece of code but with only some tiny change in their innerloops. Most often this required variation is how the algorithm outputs the results. I.e. should it replace the previous data in the output buffer, should it add it with the previous data in the buffer, or should it multiply it, etc.

Copy-pasting the whole method and changing just couple of characters from one line in the inner loop feels like an awful way to do things.

One way to cure this fairly efficiently would be to always use some simple blending formula which you give parameters, such as:

*p_buffer++ = A*(*p_buffer) + B*new_value + C;

Then you could simply give A, B and C to that algorithm and be done with it. But that feels like a waste of CPU cycles. Also if the buffer hasn't been initialized with valid float values and there's a NAN, then the results might also be NAN, even if you intend to multiply the previous value in the buffer with 0.

So is there another efficient way of creating these kinds of variations for a method without sacrificing speed? I'm hoping to have separate methods for each of the variations I use. For example:

Render();
RenderAdditive(); 
RenderMultiplicative();
RenderSomeOtherWay();

EDIT: Based on the answers, I went by defining the method as:

template<int TYPE> void Render(...)
{
    if constexpr (TYPE == 0)
        *p_output_buffer++ = data;

    if constexpr (TYPE == 1)
        *p_output_buffer++ += data;

    if constexpr (TYPE == 2)
        *p_output_buffer++ *= data;

}

This approach works great. Thank you for everyone for helping!

Upvotes: 1

Views: 93

Answers (0)

Related Questions