On the richness of C++

Bill Baxter dnewsgroup at billbaxter.com
Wed Apr 16 14:28:51 PDT 2008


MatBec wrote:
> Jason House Wrote:
> 
>> The only thing I'm contesting is your statement that closures eliminate the need for a bind library.  While it's true they reduce the need for a bind library, they don't eliminate it.
> 
> Instead of call some strange bind function just create a closure taking the still unbound arguments that calles the function.
> 
> 
> I'm not a d-Programmer, but in other languages this is very easy.
> 
> e.g. Haskell
> 
> 
> foo x y z = x + y + z
> 
> bar f = f 9
> 
> -- Pass bar a version of foo wich has two arguments bound
> bar \y -> foo 1 y 7
> 
> 
>  
> Or Ruby:
> 
> 
> def foo (x, y, z)
>    return x + y + z
> end
> 
> def bar (f)
>    return f(9)
> end
> 
> bar |y| { foo(1, y, 7) }
> 
> 
> Or in C#
> 
> int foo(int x, int y, int z)
> {
>    return x + y + z;
> }
> 
> int bar (Func<int, int> f)
> {
>    return f(9);
> }
> 
> bar(y => foo(1, y, 7));
> 
> 
> 
> Is C++'s bind realy any simpler?
> 
> 
> int foo(int x, int y, int z)
> {
>    return x + y + z;
> }
> 
> int bar (boost:function<int(int)> const & f)
> {
>    return f(9);
> }
> 
> bar(boost::bind(foo, 1, _1, 7));

Here's the D version for comparison:

int foo(int x, int y, int z)
{
    return x + y + z;
}

int bar (int delegate(int) f)
{
    return f(9);
}

bar( delegate int(int y){ return foo(1, y, 7); });

// or with inferred return type
bar( (int y){ return foo(1, y, 7); });



But that won't work if you pass it a function pointer:

int int_to_int(int x)
{
     return x+5;
}
bar( &int_to_int );

prog.d(39): function bar (int delegate(int)) does not match parameter 
types (int function(int x))
prog.d(39): Error: cannot implicitly convert expression (& int_to_int) 
of type int function(int x) to int delegate(int)

That's the main thing I'm saying.  That conversion should happen implicitly.


However, even then it would not be fully general bind replacement.  It 
still would not take a class/struct with opCall or static opCall.

struct Callme {
    int opCall(int x) {
       return x - 5;
    }
}
Callme c;
bar( c );  //.. error

bar( &c.opCall ); // this is ok, though...


Maybe the 'c' in bar(c) above should also be implicitly convertable to 
int delegate(int)?

If so then D's delegates really could eliminate the need for a bind 
template I think.  And thereby make life easier for everyone.

--bb



More information about the Digitalmars-d mailing list