Home > Software engineering >  Want to create a variable of datatype "Struct", and control (Array Size) of its sub elemen
Want to create a variable of datatype "Struct", and control (Array Size) of its sub elemen

Time:07-26

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;
}; 

CodePudding user response:

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.

CodePudding user response:

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;
};
  • Related