c++classtemplatesinstantiationconstexpr

How to create this type of C++ template array collection class with `constexpr` Compatible Instantiation


I'm wondering if it is possible on a C++ project to create a template class that allows for instantiating arrays with variable sizes, similar to the following example:

ArraysCollection<int, 3, 6, 8, 2> myArrays;

In this example, myArrays should contain arrays of different sizes, and the user can input as many sizes they want to have in the template arguments. I would also like to ensure that the class is constexpr compatible. The resulting data members of the class should be something like:

SomeType arraysCollectionData[] = {
    {0, 0, 0},
    {0, 0, 0, 0, 0, 0},
    {0, 0, 0, 0, 0, 0, 0, 0},
    {0, 0}
}

Another example:

ArrayCollection<float, 2, 3> floatArrays {
    {-10.f}, {2.f, 3.14f}
};

// results to
SomeType arraysCollectionData[] = {
    {-10.f, 0.f}, {2.f, 3.14f, 0.f}
}

I'm not quite sure how to achieve this. Can anyone provide guidance or an example of how to implement such a template class in C++ that is constexpr compatible and allows for instantiation in the specified manner?

Any help or suggestions would be greatly appreciated. Thanks in advance!


Solution

  • You can get by with an alias to a tuple of arrays, assuming you don't have other unspecified requirements.

    #include <tuple>
    #include <array>
    
    template<typename T, unsigned ...Sizes>
    using ArraysCollection = std::tuple<std::array<T, Sizes>...>;
    
    constexpr ArraysCollection<float, 2, 3> floatArrays {
        {-10.f}, {2.f, 3.14f}
    };
    

    Both those types are constexpr friendly in the latest C++ standards, and so you can use them for constant initialized objects just fine.