www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - Spec Clarification: Template Alias Parameters

reply dsimcha <dsimcha yahoo.com> writes:
Template alias parameters tend to do some strange stuff when used to alias
variables.  For example, this works:

import std.algorithm, std.stdio;

void main() {
    uint[] arr = [1,2,3,4,5];
    uint num = 3;

    bool lessThanNum(uint x) { return x < num; }
    writeln(filter!lessThanNum(arr));
}

This doesn't:

import std.algorithm, std.stdio;

class Class {
    uint toAdd = 1;

    uint doAdd(uint num) {
        return num + toAdd;
    }

    void doMap() {
        auto arr = [1,2,3,4,5];
        auto m = map!doAdd(arr);
    }
}

algorithm.d(132): Error: this for doAdd needs to be type Class not type
Map!(doAdd,int[])

I could think of countless other examples where there's no real logic behind
what works and what doesn't.  Sometimes it even depends on whether inlining is
enabled.

Since alias parameters have become an important part of idiomatic D2 code
through std.algorithm, I think we desperately need to clarify how alias
parameters are supposed to work:

1.  If you escape a struct that aliases a stack variable, is that a closure or
undefined behavior?

2.  How does aliasing a member function work?

3.  How about non-empty structs?  All kinds of erratic behavior happens when
this pointers are involved.

I feel like I can't simply file bug reports for this stuff because it's so
unclear what the correct behavior is.
Oct 20 2010
parent "Steven Schveighoffer" <schveiguy yahoo.com> writes:
On Wed, 20 Oct 2010 22:03:18 -0400, dsimcha <dsimcha yahoo.com> wrote:

 Template alias parameters tend to do some strange stuff when used to  
 alias
 variables.  For example, this works:

 import std.algorithm, std.stdio;

 void main() {
     uint[] arr = [1,2,3,4,5];
     uint num = 3;

     bool lessThanNum(uint x) { return x < num; }
     writeln(filter!lessThanNum(arr));
 }

 This doesn't:

 import std.algorithm, std.stdio;

 class Class {
     uint toAdd = 1;

     uint doAdd(uint num) {
         return num + toAdd;
     }

     void doMap() {
         auto arr = [1,2,3,4,5];
         auto m = map!doAdd(arr);
     }
 }

 algorithm.d(132): Error: this for doAdd needs to be type Class not type
 Map!(doAdd,int[])

These might be related bug reports: http://d.puremagic.com/issues/show_bug.cgi?id=3051 http://d.puremagic.com/issues/show_bug.cgi?id=3052 I'm almost positive I've seen that before in a bug report, but I couldn't find it. -Steve
Oct 21 2010