Accessing struct members with array subscript operator

后端 未结 5 1720
萌比男神i
萌比男神i 2021-01-07 10:49

Let have a type T and a struct having ONLY uniform elements of T type.

struct Foo {
    T one,
    T two,
    T three
};

I\'d like to acces

5条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-07 11:34

    You can't because the compiler can add dead bytes between members to allow padding.

    There is two ways to do what you want.

    The first is to use your compiler-specific keyword or pragma macro that will force the compiler to not add padding bytes. But that is not portable. That said it might be the easiest way to do it with your macro requirements, so I suggest you explore this possibility and prepare for adding more pragma when using different compilers.

    The other way is to first make sure your members are aligned, then add accessors :

    struct Foo {
    
       T members[ 3 ]; // arrays are guarrantied to be contigu
    
    
       T& one() { return members[0]; } 
       const T& one() const { return members[0]; } 
       //etc... 
    
    };
    

提交回复
热议问题