Search code examples
c++arrayssizeexternal

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

Solution

  • 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.