中优雅地定义多维数组

中优雅地定义多维数组

本文介绍了在现代C ++中优雅地定义多维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用T[][][]语法定义多维数组很容易.但是,这会创建一个原始数组类型,该类型不太适合现代C ++.这就是为什么自C ++ 11起我们就有std::array的原因.但是使用std::array定义多维数组的语法非常混乱.例如,要定义三维int数组,您必须编写std::array<std::array<std::array<int, 5>, 5>, 5>.语法根本无法扩展.我正在寻求解决此问题的方法.也许,不能使用C ++提供的现有实用程序解决此问题.在那种情况下,我对开发用于简化语法的自定义工具感到满意.

Defining multi-dimensional array using the T[][][] syntax is easy. However, this creates a raw array type which doesn't fit nicely into modern C++. That's why we have std::array since C++11. But the syntax to define a multi-dimensional array using std::array is quite messy. For example, to define a three-dimensional int array, you would have to write std::array<std::array<std::array<int, 5>, 5>, 5>. The syntax doesn't scale at all. I'm asking for a fix for this issue. Maybe, this issue cannot be fixed using existing utility provided by C++. In that case, I'm happy with a custom tool developed to ease the syntax.

找到了一个解决方案我自己:

template <typename T, std::size_t n, std::size_t... ns>
struct multi_array {
  using type = std::array<typename multi_array<T, ns...>::type, n>;
};

template <typename T, std::size_t n>
struct multi_array<T, n> {
  using type = std::array<T, n>;
};

template <typename T, std::size_t... ns>
using multi_array_t = typename multi_array<T, ns...>::type;

想知道实施是否可以进一步简化.

Wondering whether the implementation can be further simplified.

推荐答案

请参阅 C ++ 11中的多维数组

template <class T, std::size_t I, std::size_t... J>
struct MultiDimArray
{
  using Nested = typename MultiDimArray<T, J...>::type;
  // typedef typename MultiDimArray<T, J...>::type Nested;
  using type = std::array<Nested, I>;
  // typedef std::array<Nested, I> type;
};

template <class T, std::size_t I>
struct MultiDimArray<T, I>
{
  using type = std::array<T, I>;
  // typedef std::array<T, I> type;
};

MultiDimArray<float, 3, 4, 5, 6, 7>::type floats;

MultiDimArray是一对用于计算多维std::array的嵌套类型的元函数.最通用的MultiDimArray是无符号整数的可变参数模板,用于传递任意数量的维.终止的MultiDimArray专业化定义一维std::array的最简单情况.

MultiDimArray is a pair of meta-functions to compute nested type for multi-dimensional std::array. The most general MultiDimArray is a variadic template of unsigned integers to pass an arbitrary number of dimensions. The terminating MultiDimArray specialization defines the simplest case of single dimensional std::array.

这篇关于在现代C ++中优雅地定义多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 13:06