D equivalent of C++ bind ?
Dsby via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Thu May 12 03:38:37 PDT 2016
On Tuesday, 10 May 2016 at 09:39:53 UTC, chmike wrote:
> Is there an equivalent in D of the C++11 std.bind template
> class
> [http://en.cppreference.com/w/cpp/utility/functional/bind] ?
>
> Here is a blog post showing different examples of its use
> https://oopscenities.net/2012/02/24/c11-stdfunction-and-stdbind/
>
>
> A possible use case is for a callback function/delegate with
> the expected signature bool cb(int error). I would like to pass
> a function bool myCb(int error, ref int myArg) instead with the
> variable myArg being given as predefined argument.
>
> Here is an example.
> ----
> int count = 0;
>
> bool myCb(int error, ref int myArg)
> {
> if (myArg >= 6)
> return false;
> writeln(++myArg);
> return true;
> }
>
> void async_task(void function(int error) cb) { . . . while
> cb(0) . . . }
>
> void main() {
> . . .
> async_task( ??? myCb ??? count ??? );
> . . .
> }
> ----
>
> In C++ we would write
>
> async_task(std::bind(myCb, std::placeholders::_1, count));
I write one, bind functon to a delegate.
In here:
https://github.com/putao-dev/collie/blob/master/source/collie/utils/functional.d
this is the code:
auto bind(T,Args...)(auto ref T fun,Args args) if
(isCallable!(T))
{
alias FUNTYPE = Parameters!(fun);
static if(is(Args == void))
{
static if(isDelegate!T)
return fun;
else
return toDelegate(fun);
}
else static if(FUNTYPE.length > args.length)
{
alias DTYPE = FUNTYPE[args.length..$];
return
delegate(DTYPE ars){
TypeTuple!(FUNTYPE) value;
value[0..args.length] = args[];
value[args.length..$] = ars[];
return fun(value);
};
}
else
{
return delegate(){return fun(args);};
}
}
More information about the Digitalmars-d-learn
mailing list