tags:

views:

130

answers:

1

Don't know if is possible, I want receive maybe data[n] or data[n][n][n]. In C could be (correct me if wrong):


void save_data(void* arr, int n, int dimensions)
{
    // do ugly things
}

But must exist a more elegant way in D.

+6  A: 

One alternative besides using C style pointer arithmetics is to template safe_data, i.e. do something like this:

import std.stdio;
import std.traits;

void safe_data(T)(in T arr) {
    static if(isArray!T) {
        writeln("Length ", arr.length); // do some ugly stuff for whole array
        foreach(e; arr) safe_data(e);   // recursively go deeper
    } else {
        writeln("Element ", arr);       // do more ugly stuff on individual elements
    }
}

void main() {
    writeln("A");
    int[3] A = [1,2,3];
    safe_data(A);
    writeln("B");
    int[3][2] B = [[1,2,3],[4,5,6]];
    safe_data(B);
}

Depending on what you want to do with the data, you might want to use ref instead on in. BTW, if you prefer, you can move the static if outside of the function which makes for cleaner code sometimes:

// handle arrays
void safe_data(T)(in T arr) if(isArray!T) {
        writeln("Length ", arr.length); // do some ugly stuff for whole array
        foreach(e; arr) safe_data(e);   // recursively go deeper
}

// handle array elements
void safe_data(T)(in T e) if(!isArray!T) {
        writeln("Element ", e);         // do more ugly stuff on individual elements
}
stephan
Just what I was looking for! I don't understand well templates but your example is very elucidatory.
Pedro Lacerda
@Pedro: you are welcome. If you want to serialize data, Orange (http://www.dsource.org/projects/orange) might be worth a look.
stephan