Would you believe that the capacity to do this is built into C++ with templates?
I’m looking at a paper by Todd Veldhuizen entitled “C++ Templates As Partial Evaluation”, in which he describes various weird things that you can do with templates in C++. One of them is performing compile-time calculations, and he gives the example of creating an array with a non-constant size using a strange sequence of template functions. This may be what the OP’s professor had in mind. The paper is available online, but I lost the link.
There are a few other tricks shown in there. It’s very interesting reading, especially if you thought that templates could only be used to write generic code.
I’d really like to see how anybody could invent a template (a compile-time generator of code) that could specify a run-time specified array size without dynamic allocation. Either the template you’re talking about is only allowing compile-time selection of array size (which doesn’t solve the problem), or its using dynamic allocation.
By definition a compiler can only work out compile-time issues from compile-time available information, which is all that templates have available to them. Unless I’ve misinterpreted the OP, the idea is to have run-time selectable array size.
Unless there’s some truly impressive uses for templates I don’t yet know about, which is perfectly possible!
Okay, I’ve studied the paper (very cool paper by the way!), but I still don’t see how you could invent an array with a run-time decided array size using templates, but not using dynamic allocation.
I will say that my solution above definitely would benefit from being templatized to turn the BLOCKSIZE, callback function type, element type, and parameter block type into compile time decisions and remove DynamicArray’s dependancy on specific types and constant sizes. I’ve pondered doing this just to prove it can be done. However, nothing can be done about the need to determine at run-time the amount of space needed.
Please, I’d love to be proven wrong! It would mean I’d learn something even more twisted and demented about the language.
Use the code in section 2.2 of that paper (which doesn’t compile under MSVC++ 6.0, grumble, grumble), but read in the values of Length and Dims. That should work, unless there’s some subtlety that I’m missing.
Yes… the length and dims needs to be constant at compile time. No compiler should accept run-time valued parameters for the template parameters in that context.