简体   繁体   English

如何在类模板整数列表上展开?

[英]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. 因此,我一直在尝试学习有关c ++元编程的更多信息,并且一直试图设计一个长度可变的元组。

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. 第一个参数' float '是数组将存储的数据类型。 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. 我建议您使用std::array而不是自定义数组或旧的C样式数组。

If you want a variadic list of std::array , you can use std::tuple and write something like 如果您想要std::array的可变列表,则可以使用std::tuple编写类似

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

You can also try using C-style arrays 您也可以尝试使用C样式的数组

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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