简体   繁体   English

用静态2d数组定义类的便捷方法是什么(只有在编译时才知道2d数组的大小)?

[英]What is a convenient way to define a class with a static 2d array (and the size of the 2d array is known only during compile time)?

The sample code below shows what I am trying to do: 下面的示例代码显示了我正在尝试做的事情:

template<int NX, int NY>
class Array
{
public:
  float v[NX][NY];
};

void main()
{
  Array<10,20> grid;
}

The above code won't compile, but it shows what I want to do. 上面的代码不会编译,但是显示了我想要执行的操作。 We have a class that contains an array, and the array class doesn't know its size until compile time. 我们有一个包含数组的类,该数组类直到编译时才知道其大小。 Is there a simple way to do this? 有没有简单的方法可以做到这一点?

Edit: I want to write a simple reusable array class. 编辑:我想编写一个简单的可重用数组类。 That means I need to find a good way to separate the array size from the class. 这意味着我需要找到一种从类中分离数组大小的好方法。

I also want the class to be fast (and simple) so it must not be dynamically allocated. 我还希望该类快速(且简单),因此不能动态分配。 That means the size can't be given during run time. 这意味着无法在运行时指定大小。

I also don't want to use the preprocesser to define the size because that means I will have to go through the hassle of changing a number somewhere. 我也不想使用预处理器来定义大小,因为这意味着我将不得不经历在某个地方更改数字的麻烦。 That isn't convenient enough. 这还不够方便。

Basically, the class doesn't know its own size until compile time, because that is when the main function tells the class its size. 基本上,该类直到编译时才知道其自身的大小,因为那是主函数告诉该类其大小的时候。

Edit: The above code is good. 编辑:上面的代码是好的。

Other than main not returning an int , this is legal code and should compile. 除了main不返回int ,这是合法代码,应编译。 In fact, on some compilers this will compile without main returning an int , such as VC++ but this is non-standard behaviour . 实际上,在某些编译器上,它将在编译时不需要main返回int ,例如VC ++,但这是非标准行为

You can also store the size at compile time so that you don't have to calculate it manually. 您还可以在编译时存储大小,从而不必手动计算。

#include <iostream>

template<int NX, int NY>
class Array
{
public:
  float v[NX][NY];

  int size() const { return ArraySize; }

private:
  enum { ArraySize = NX * NY }; // You can also store rows/cols individually
};

int main()
{
  Array<10,20> grid;

  std::cout << grid.size();

  return 0;
}

Boost.MultiArray可能适合您的需求。

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

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