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.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With