简体   繁体   中英

How to expand on a class template integer list?

So I've been trying to learn more about c++ metaprogramming and I'm stuck in trying to design a tuple of varying length arrays.

The idea of what I want to do is something like this:

CustomArrays<float, 3, 2> arrays;

The first argument ' float ' is the type of data the arrays will store. The arguments following are the lengths of each array. I can make a struct like this that takes these arguments:

template <typename T, uint... As> struct CustomArrays {};

I know that if I only took one argument instead of a list I could store the array like this:

template <typename T, uint A> struct CustomArrays { T data[A]; };

This is what I want but with the expanded subclasses, similar to what the tuple could do. I'm thinking something along this:

template <typename T, uint A> struct CustomArrays {};

template <typename T, uint A, uint... As>
struct CustomArrays : CustomArrays<T, As...> {
    T data[A];
};

The idea is to have this expand like this:

struct CustomArrays<float, 2, 3> : CustomArrays<float, 3> {
    float data[2];
}

struct CustomArrays<float, 3> : CustomArrays {
    float data[3];
}

struct CustomArrays {}

This of course doesn't compile since we redeclare the same struct with different template parameters. My question is how can I achieve the desired outcome.

I suggest you to use std::array instead custom arrays or old C-style arrays.

If you want a variadic list of std::array , you can use std::tuple and write something like

template <typename T, std::size_t ... Dims>
struct CustomArrays
 { std::tuple<std::array<T, Dims>...> data; };

You can also try using C-style arrays

template <typename T, std::size_t ... Dims>
struct CustomArrays
 { std::tuple<T[Dims]...> data; };

but I don't think it's a good idea.

You might be looking for something like this:

template <typename T, uint... As> struct ArrayType;

template <typename T>
struct ArrayType<T> {
    typedef T type;
};

template <typename T, uint A, uint... As>
struct ArrayType<T, A, As...> {
    typedef typename ArrayType<T, As...>::type type[A];
};

template <typename T, uint... As>
struct CustomArrays {
  typename ArrayType<T, As...>::type data;
  // CustomArrays<float, 3, 2>::data is of type float[3][2]
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM