Search code examples
arraysd

Mechanics behind adding two arrays in D language


I am a bit curious mechanics behind code below:

int[3] a1 = [ 1 , 2 , 3 ];
int[3] a2 = [ 1 , 2 , 3 ];
int[3] result = a1[] + a2[];
foreach (i; result)
    writeln(i);

Result is 2,4,6 . In C++ we had to overload '+' operator for it to take two vectors to achive this or use std::transform. I checked a little the implementation doc of array(std_array.html). I couldn't find out any overload for '+', I think D is somehow managing this by checking if the data integral type or something but I am just guessing.

Can somebody explain how this actually works?


Solution

  • It is part of the language itself:

    http://dlang.org/arrays.html#array-operations

    The implementation may do different things as long as it gives the result, which gives enough flexibility for automatic optimizations. Currently, looking at a disassembly, it compiles to a function call, similar to an operator overload, just done automatically.