简体   繁体   中英

Want to create a variable of datatype "Struct", and control (Array Size) of its sub element from outside

I want to feed SIZE externally while declaring a variable of datatype "Struct". Basically I want to use this datatype with different size.

struct ArrStruct final
{
    std::array<float32_t, SIZE> Arr1;
    std::array<float32_t, SIZE> Arr2;
};

struct Type1 final
{
    ArrStruct          var4;
    float32_t          var5;
};

struct StructData final
{
    Type1           var1;
    float32_t       var2;
    float32_t       var3;
};


struct Struct final
{
    StructData         Data;
}; 

you can use a c++ macro in this case called SIZE. Also I failed to find a float32_t data type so I just went with float which has a size of 32 bits.

#define SIZE 3

struct ArrStruct final
{
    std::array<float, SIZE> Arr1;
    std::array<float, SIZE> Arr2;
};

You can make SIZE a template argument:

template <size_t SIZE>
struct ArrStruct final
{
    std::array<float32_t, SIZE> Arr1;
    std::array<float32_t, SIZE> Arr2;
};

template <size_t SIZE>
struct Type1 final
{
    ArrStruct<SIZE>    var4;
    float32_t          var5;
};

template <size_t SIZE>
struct StructData final
{
    Type1<SIZE>     var1;
    float32_t       var2;
    float32_t       var3;
};

template <size_t SIZE>
struct Struct final
{
    StructData<SIZE>     Data;
}; 

Struct<42> is then a Struct with a StructData<42> which in turn has a member of type Type1<42> and that has a member of type ArrStruct<42> which contains arrays of size 42 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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