Ivaylo Valchev
Ivaylo Valchev

Reputation: 10425

A class with an array member of generic rank

Consider the following code sample:

#include <iostream>
#include <tuple>

template<typename T, std::size_t Rank, std::size_t... In>
struct help;

template<typename T, std::size_t... In>
struct help<T, 1, In...> 
{
    static constexpr auto a = std::make_tuple(In...);
    T data[std::get<0>(a)];
};

template<typename T, std::size_t... In>
struct help<T, 2, In...>
{
    static constexpr auto a = std::make_tuple(In...);
    T data[std::get<0>(a)][std::get<1>(a)];
};

template<typename T, std::size_t... In>
class foo : public help<T, sizeof...(In), In...>
{
private:
    using base = help<T, sizeof...(In), In...>;

public:
    template<typename... Tn>
    constexpr foo(Tn&&... args)
        : base{ { args... } } // constructor would only work if rank == 1
    {}
              T operator[](std::size_t i)       noexcept { return base::data[i]; }
    constexpr T operator[](std::size_t i) const noexcept { return base::data[i]; }
};

int main() 
{   
    foo<int, 6> a = {  1, 2, 3, 4, 5, 6  };

    for (std::size_t i = 0; i < 6; ++i) {
        std::cout << a[i] << " ";
    }
}  

This is as far as I got.

I'm trying to make a class, objects of which shall be constructed as foo<int, 2>; foo<int, 3, 4>; foo<int, 1, 2, 3, 4>; These objects will hold an array member respectively of type int[2]; int[3][4]; int[1][2][3][4].

My initial thinking was to make a helper template class which would specialize quite a lot (at least until an array of rank 20). That is obviously verbose, and after I get to an array of rank 2, I have no idea what the constructor for foo should be.

The constructor problem can be solved by making the class a POD (no access specifiers, etc) and construct via aggregate initialization (much like std::array does), but that goes against my work so far with the "proper inherited specialization".

I would appreciate some ideas. How would you go about doing something like this?

Upvotes: 2

Views: 206

Answers (1)

Barry
Barry

Reputation: 303537

I think you're overcomplicating things. Just make a type trait that gives you the correct std::array type:

template <class T, size_t... Is>
struct multi_array;

template <class T, size_t... Is>
using multi_array_t = typename multi_array<T, Is...>::type;

With zero dimensions, you just get the type:

template <class T>
struct multi_array<T> {
    using type = T;
};

and with at least one dimension, you just wrap it in std::array and recurse:

template <class T, size_t I, size_t... Is>
struct multi_array<T, I, Is...> {
    using type = std::array<multi_array_t<T, Is...>, I>;
};

So you get something like:

static_assert(std::is_same<multi_array_t<int, 2>, std::array<int, 2>>::value, "!");
static_assert(std::is_same<multi_array_t<int, 3, 4>, std::array<std::array<int, 4>, 3> >::value, "!");

Upvotes: 6

Related Questions