方法自动字段类似C结构重新排序字段、类似、结构、方法

2023-09-11 07:44:25 作者:路亽曱

有没有办法来执行automatic场在C-状结构重新排序?我的意思是使用类似(preprocessor的C和C ++和模板/类型特征的/ etc C ++),这使得它可以做到下面的宏(Boost.Fusion般的风格,以适应结构)的语言特征:

Is there a way to perform automatic fields reordering in C-like structs? I mean the using of the language features like( preprocessor for C and C++ and templates/type traits/etc for C++), which make it possible to do the following macro (Boost.Fusion-like style to adapt structures):

REARRANGE(StructureName,
          (int8_t)(FieldName1),
          (int32_t)(FieldName2),
          (int16_t)(FieldName3),
          (int32_t)(FieldName4));
// is equivalent to (without loss of generality):
struct StructureName
{

    int32_t FieldName2;
    int32_t FieldName4;
    int16_t FieldName3;
    int8_t FieldName1;

};

当然,办法应考虑到 alignof 值(连同的sizeof )的领域,如果它可能的话,的#pragma包当前值。

Of course, approach should take into account alignof values (together with sizeof) for fields and, if it possible, #pragma pack current value.

我知道不好结果的便携性,但是它对于本地使用。

I am aware of bad portability of the result, but it for local use only.

这是强制性的东西保存的字段名称以及各自的类型。

It is mandatory thing to save the field names together with respective types.

其目的是降低总结构尺寸

The aim is to reduce total structure size.

推荐答案

对于MS编译器使用的#pragma包,(的#pragma包( 1)消除了所有的空白)。而检查链接的详细信息,因为该指令不能保证总是工作。 对于GCC有 __ attribute__((打包))

For MS compiler use #pragma pack, (#pragma pack(1) eliminates all gaps). And check the link for details, as this directive is not guaranteed to work always. For GCC there is __attribute__ ((packed))

作为你唯一的目标就是在内存中的数据的最小可能的大小,这正是你需要的。

As your only goal is the minimal possible size of the data in memory, this is exactly what you need.

 
精彩推荐
图片推荐