www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.bugs - [Issue 5127] New: Template instantiation arguments with integer operations

reply d-bugmail puremagic.com writes:
http://d.puremagic.com/issues/show_bug.cgi?id=5127

           Summary: Template instantiation arguments with integer
                    operations
           Product: D
           Version: D2
          Platform: All
        OS/Version: All
            Status: NEW
          Keywords: rejects-valid
          Severity: enhancement
          Priority: P2
         Component: DMD
        AssignedTo: nobody puremagic.com
        ReportedBy: bearophile_hugs eml.cc


--- Comment #0 from bearophile_hugs eml.cc 2010-10-28 14:42:11 PDT ---
This is a correct D2 program. Given an array, doubleit() returns an array with
two copies of each item, in this example doubleit() outputs [1, 1, 2, 2, 3, 3,
4, 4], the return type is a twice long array of ints:


T[n+n] doubleit(T, int n)(T[n] data) {
    typeof(return) result;
    foreach (i, x; data) {
        result[i * 2] = x;
        result[i * 2 + 1] = x;
    }
    return result;
}
void main() {
    int[4] v = [1, 2, 3, 4];
    int[8] r = doubleit(v);
}




This is a similar program, but it currently doesn't compile:


void doubleit(T, int n)(T[n] data, out T[n+n] result) {
    foreach (i, x; data) {
        result[i * 2] = x;
        result[i * 2 + 1] = x;
    }
}
void main() {
    int[4] v = [1, 2, 3, 4];
    int[8] r;
    doubleit(v, r);
}


DMD 2.050beta shows the errors:

test.d(1): Error: Integer constant expression expected instead of n + n
test.d(10): Error: template test2.doubleit(T,int n) does not match any function
template declaration
test.d(10): Error: template test2.doubleit(T,int n) cannot deduce template
function from argument types !()(int[4u],int[8u])


The type inferencing of the template instantiation is able to perform and test
n+n for return value length, but it's not currently able to do it for that out
argument.

This missing capability is generally useful for data structures that are
defined on one or more compile-time integer values (as fixed-sized arrays here)
(For more info search for "number parameterized types" with Google).

-- 
Configure issuemail: http://d.puremagic.com/issues/userprefs.cgi?tab=email
------- You are receiving this mail because: -------
Oct 28 2010
parent d-bugmail puremagic.com writes:
http://d.puremagic.com/issues/show_bug.cgi?id=5127



--- Comment #1 from bearophile_hugs eml.cc 2010-10-28 16:34:23 PDT ---
Currently the best workaround for that limitation is to use a template
constraint:


void doubleit(T, int n, int m)(T[n] data, out T[m] result) if (m == n+n) {
    foreach (i, x; data) {
        result[i * 2] = x;
        result[i * 2 + 1] = x;
    }
}
void main() {
    int[4] v = [1, 2, 3, 4];
    int[8] r;
    doubleit(v, r);
}

-- 
Configure issuemail: http://d.puremagic.com/issues/userprefs.cgi?tab=email
------- You are receiving this mail because: -------
Oct 28 2010