Can't use map (and friends) for virtual functions?

Andrej Mitrovic none at none.none
Mon Apr 25 16:44:43 PDT 2011


import std.algorithm;

struct Foo
{
    int bar(string) { return 1; }
    
    void run()
    {
        auto result = map!(bar)(["test"]);
    }
}

void main()
{   
}

D:\DMD\dmd2\windows\bin\..\..\src\phobos\std\algorithm.d(128): Error: this for bar needs to be type Foo not type Map!(bar,string[])

I can't use a virtual function as an alias parameter to a template, it either has to be a free function or a static function.

So basically I have to use delegates:

import std.algorithm;
import std.traits;
import std.stdio;

auto myMap(Delegate, Range)(Delegate dg, Range t)
{
    ReturnType!(dg)[] result;
    
    foreach (val; t)
    {
        result ~= dg(val);
    }
    
    return result;
}

struct Foo
{
    int bar(string) { return 1; }
    
    void run()
    {
        auto result = myMap(&bar, ["test", "test"]);
        writeln(result);
    }
}

void main()
{
    auto foo = Foo();
    foo.run();
}

But this means I have to take every Phobos function which I need and which takes an alias and convert it to a delegate version if I ever want to use it inside a struct or a class for non-static functions.

Can't Phobos functions be made smarter so they work with virtual functions? Or would "alias" need re-engineering?


More information about the Digitalmars-d-learn mailing list