Search code examples
d

Non Member range functions


I have a class that I'm implementing ranges for. I'd like to implement the functions the way the phobos library does, i.e. outside the main class.

void popBack(T)(ref T[] a) if (!is(Unqual!T == char) && !is(Unqual!T == wchar))
{
    assert(a.length);
    a = a[0 .. $ - 1];
}

Here's my version:

void popFront(T)(ref PersistentList!(T) a)
{
    a = a.next();   
}

When I try to compile this code with a forech, I get:

Error   1   Error: no property 'popFront' for type 'stmd.PersistentList!(int).PersistentList'   main.d  

I could move the member code into the main class, but since I'm modifying the input "ref" value I can't use popFront() I really need popFront(ref a).

What am I doing wrong?


Solution

  • What you're trying to do depends on what the D community calls uniform function call syntax. This is the ability to call non-member functions with the same syntax as member functions. This has been implemented for arrays only for a long time, and there was some debate about how far to take it. It's been decided that it should be implemented for all types, but Walter Bright, the compiler implementer hasn't gotten around to doing this yet because he's been working feverishly on 64-bit support.

    Uniform function call syntax is described in Andrei Alexandrescu's book, "The D Programming Language", which is considered the authoritative guide to D2. Its currently lack of implementation is considered a bug. This should be fixed in a few releases.