www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Can't use map (and friends) for virtual functions?

reply Andrej Mitrovic <none none.none> writes:
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?
Apr 25 2011
parent reply bearophile <bearophileHUGS lycos.com> writes:
Andrej Mitrovic:

 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.

Where's the virtual function? Bye, bearophile
Apr 26 2011
next sibling parent "Steven Schveighoffer" <schveiguy yahoo.com> writes:
On Tue, 26 Apr 2011 07:24:28 -0400, bearophile <bearophileHUGS lycos.com>  
wrote:

 Andrej Mitrovic:

 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.

Where's the virtual function?

I think he means member function. Clearly the function is not virtual. -Steve
Apr 26 2011
prev sibling parent Andrej Mitrovic <andrej.mitrovich gmail.com> writes:
Yeah my bad, I've cut&paste code while thinking of similar code.
Apr 26 2011