0

Consider such a class

template<int n, class T>
class dimArray {
    T* arr;
    int len[n];
public:
    dimArray(int len₀, int len₁, int len₂, ..., int lenₕ₋₁, T initValue);
    T& at(int x₀, int x₁, int x₂, ..., int xₕ₋₁);
    void foo(int x₀, int x₁, int x₂, ..., int xₕ₋₁, .../*va_args*/);
}

used by

dimArray<2, double> a(3,4, 1.0);
a.at(1,2) = 4.3;
std::cout << a.at(2,3);
a.foo(1,2, 7.3,4.2,0);

The len₀ etc. are p code. Is it possible to make such thing in C++? If so, how?

l4m2
  • 1,157
  • 5
  • 17

1 Answers1

1

You might do it with variadic template and std::index_sequence utility:

template <std::size_t I, typename T>
using always_t = T;

template<typename Seq, class T>
class dimArrayImpl;

template<std::size_t ... Is, class T>
class dimArrayImpl<std::index_sequence<Is...>, T>
{
    T* arr;
    int len[sizeof...(Is)];
public:
    dimArrayImpl(always_t<Is, int>... lens, T initValue);
    T& at(always_t<Is, int>... lens);
    void foo(always_t<Is, int>... lens, .../*va_args*/);
};

template<int n, class T>
using dimArray = dimArrayImpl<std::make_indexsequence<n>, T>;
Jarod42
  • 203,559
  • 14
  • 181
  • 302
  • Is this C++14 based? – l4m2 Jan 06 '19 at 08:09
  • `std::index_sequence` is indeed c++14, but can be implemented in C++11. Variadic template is from C++11. To "simulate" it in C++98, you have to write up to N specializations, (mostly duplicate code for each version) or use fixed number with special type... – Jarod42 Jan 06 '19 at 08:14