How does sizeof work? How can I write my own?

后端 未结 10 2337
粉色の甜心
粉色の甜心 2021-02-08 07:29

I know C++ and know the function sizeof itself but I need to write my own sizeof function so please explain how it works exactly? What does it do with the parameter

10条回答
  •  既然无缘
    2021-02-08 08:28

    I saw this post when searching for a way to get the same functionality as the sizeof operator. It turned out that I implemented a function called bit_sizeof() that looks a lot like the operator sizeof, but which returns the number of bits of a given type instead. I implemented a global template function like this:

    #include    //For CHAR_BIT
    
    //Global function bit_sizeof()
    template
    constexpr uint32_t bit_sizeof(TSizeOfType)
    {
       return (sizeof(TSizeOfType) * CHAR_BIT);
    }
    

    This function requires the use of the c++11 standard, as it uses the keyword constexpr. Without the keyword constexpr, the function will compile still. But the compiler may not optimize properly and put in a function call at each call site of using the bit_sizeof function. With the use of constexpr, the whole function evaluates to a constant, which in my knowledge should be exactly equivalent to how the sizeof operator works? Correct me if I am wrong. In use I call the function like this, with an added parantesis after the type:

    uint32_t uiBitsInType = bit_sizeof(char());
    

    The function can be useful when creating bit masks for example:

    uint32_t uiMask = (((uint32_t(0x1) << bit_sizeof(char())) - 0x1) << bit_sizeof(char()));
    

    Which could be more readable than this:

    uint32_t uiMask2 = (((uint32_t(0x1) << (sizeof(char) * 0x8)) - 0x1) << (sizeof(char) * 0x8));
    

    Personally I have other uses for this function also.

提交回复
热议问题