0

I have a class to calculate CRC using table maethod that looks like this (it is incomplete):

template<typename CrcBaseType, uint32_t Polynomial, uint32_t InitialValue, uint32_t XorOut, bool ReverseInput, bool ReverseOutput>
requires std::unsigned_integral<CrcBaseType>
class CrcDriver{
public:
    CrcDriver() {};
private:
    const CrcBaseType table[256];
    const uint8_t size = sizeof(CrcBaseType);
private:
    constexpr void genTable() {
        for (uint32_t divident = 0; divident < 256; divident++) {
            uint32_t curByte = divident << (8 * (size - 1));
            for (uint8_t bit = 0; bit < 8; bit++) {
                if ((curByte & (0x80 << (8 * (size - 1)))) != 0)
                {
                    curByte <<= 1;
                    curByte ^= Polynomial;
                }
                else
                {
                    curByte <<= 1;
                }
            }
            table[divident] = curByte & (0xFFFFFFFF >> (4 - size) * 8);
        }
    }

    constexpr void genTableR() {
        Polynomial = ReverseWord(Polynomial) >> (4 - size) * 8;
        for (uint32_t divident = 0; divident < 256; ++divident) {
            uint32_t curByte = divident;
            for (uint8_t bit = 0; bit < 8; bit++) {
                if ((curByte & 0x00000001) != 0)
                {
                    curByte >>= 1;
                    curByte ^= Polynomial;
                }
                else
                {
                    curByte >>= 1;
                }
            }
            table[divident] = curByte & (0xFFFFFFFF >> (4 - size) * 8);
        }
    }
};

I do not have any need to redefine it in runtime. How can I use constexpr genTable/R to populate table at compile time?

lazba
  • 129
  • 9
  • 1
    Use a `std::array`. Then you can create a function that generates the `std::array` and in your class you just use `const std::array table = my_helper_function();` – NathanOliver Mar 23 '23 at 17:43
  • I use this class on ebedded, and std::array seems to have more cost than c-style arrays – lazba Mar 23 '23 at 17:47
  • 1
    `std::array` should have the same cost as a raw array, as long as you compile with optimizations turned on. – NathanOliver Mar 23 '23 at 17:49
  • @lazba It does not. It's just `template struct array { T arr[S]; };` plus some member functions. You may incur a slight _compile_ time cost, but for any halfway decent optimizing compiler there should be no measurable difference at runtime. – Miles Budnek Mar 23 '23 at 17:50

0 Answers0