Search code examples
c++if-constexpr

Inline function with one of two parameters as constexpr


Assume I have a function with two parameters where first parameter is dynamic but second parameter is always constant known at compile time:

uint8_t convert_bcd(uint8_t num, uint8_t mask) {
    uint8_t result = mask & 0x0F & num;

    if constexpr ((mask & 0xF0) != 0) // mask is known at compile time, can be optimized
        result += 10 * ((mask & 0xF0 & num) >> 4);

    return result;
}

Example usage

uint8_t result1 = convert_bcd(data[0], 0x7F);
uint8_t result2 = convert_bcd(data[1], 0x3F);

I would want to inline this function (if possible) and tell the compiler that the if condition, which involves only second parameter which always constant, can be resolved at compile time.

I got confused with inline/const/constexpr and how to apply them in my scenario to optimize the function as much as possible.

What is the proper idiomatic way to do it in C++?


Solution

  • Write a template.

    template<uint8_t mask>
    uint8_t convert_bcd(uint8_t num) {
        uint8_t result = mask & 0x0F & num;
    
        if constexpr ((mask & 0xF0) != 0)
            result += 10 * ((mask & 0xF0 & num) >> 4);
    
        return result;
    }
    
    
    uint8_t result1 = convert_bcd<0x7F>(data[0]);
    uint8_t result2 = convert_bcd<0x3F>(data[1]);