Map and arrays

bearophile bearophileHUGS at lycos.com
Sun Nov 28 03:19:00 PST 2010


Tom:

> What should I do? Is there some way to get the original array type?

This code shows two ways to solve your problem:


import std.stdio: writeln;
import std.algorithm: map;
import std.conv: to;
import std.traits: ForeachType;
import std.array: array;

void foo(Range)(Range srange) if (is(ForeachType!Range == string)) {
     writeln(srange);
}

void bar(string[] sarray) {
     writeln(sarray);
}

void main() {
    int[] arr = [1, 2, 3];
    auto srange = map!(to!string)(arr);
    foo(srange);
    string[] sarr = array(srange);
    bar(sarr);
}


They are good for different purposes, but in many cases the foo() version is good.

If you want to simplify your code a little you may define a helper template like this:

template IsIterableType(Range, T) {
    enum bool IsIterableType = is(ForeachType!Range == T);
}

void foo2(Range)(Range srange) if (IsIterableType!(Range, string)) {
     writeln(srange);
}

Bye,
bearophile


More information about the Digitalmars-d-learn mailing list