How to flatten N-dimensional array?

Ali Çehreli acehreli at yahoo.com
Mon May 25 01:00:45 UTC 2020


On 5/24/20 2:37 AM, Pavel Shkadzko wrote:
> On Saturday, 23 May 2020 at 19:59:30 UTC, Ali Çehreli wrote:
>> On 5/23/20 11:15 AM, Pavel Shkadzko wrote:> I have tried to implement 
>> a simple flatten function for multidimensional
>>
>> [...]
> 
> Thank you, I was lacking practical examples for templates with "if" 
> constructs, ehh.

Template constraints are great but 'static if' can be more useful as it 
allows custom error messages:

auto makeNdim(size_t N)(size_t length) {
   static if (N == 1) {
     auto result = iota(value, value + length).array;
     value += length;
     return result;

   } else static if (N > 1) {
     return iota(N).map!(n => makeNdim!(N - 1)(length)).array;

   } else {
     static assert(false, "N cannot be 0.");
   }
}

Ali



More information about the Digitalmars-d-learn mailing list