简体   繁体   English

C ++如何获取位域成员的大小?

[英]C++ How to get the size of bitfield members?

I try to get the size of a bitfield. 我试图得到一个位域的大小。

For example, I have got a generic handle: 例如,我有一个通用句柄:

template<size_t n, size_t m>
struct handle
{
    uint32 index : n; 
    uint32 validation : m;
}

Now I want to get the size of the members. 现在,我想获取成员的人数。

I found a macro that works when I have a handle<16, 16> and expands the desired members to sizeof . 我找到了一个宏,当我具有handle<16, 16>并将其扩展为sizeof In this case, if I pass in the index members I get 16 as my output. 在这种情况下,如果传入index成员,则输出为16

But there I would have to pass in my output variable. 但是在那里,我必须传递我的输出变量。

Is there a way maybe with some template magic to expand directly to the desired number? 有没有办法用一些模板魔术直接扩展到所需的数字? So I could pass in sizeof_bit(class, member) and I get the sizebit size of this member? 所以我可以传入sizeof_bit(class, member)然后得到这个成员的sizebit大小?

Maybe something like 也许像

template<size_t n, size_t m>
struct handle
{
    enum { index_bits = n };
    enum { validation_bits = m };
    uint32_t index : n; 
    uint32_t validation : m;
};

Demo . 演示

If you have no control over the structure defining the bitfield, you can do something like this to count the number of bits in it at run time, but it's fairly inefficient. 如果你有过定义位域结构无法控制,你可以做一些像这样算在运行时在其位的数量,但它的效率非常低。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM