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
mainnot returning anint, this is legal code and should compile. In fact, on some compilers this will compile withoutmainreturning anint, such as VC++ but this is non-standard behaviour.You can also store the size at compile time so that you don’t have to calculate it manually.