On 11/09/2012 10:30 AM, Manfred Nowak wrote:
> Jack Applegame wrote:
>
>> Ok. Then how to implement in D this С++ std::function feature?
>>
>> http://liveworkspace.org/code/01aa058901529f65cb9a3cc4ba605248
>
> That feature is among others defined here:
> http://en.cppreference.com/w/cpp/utility/functional/function

The following D program produces the same output as the C++ example there:

import std.stdio : writeln;
import std.functional : curry;

struct Foo
{
    int num;

    void print_add(int i)
    {
        writeln(num + i);
    }
}

void print_num(int i)
{
    writeln(i);
}

void main()
{
    // store a free function
    auto f_display = &print_num;
    f_display(-9);

    // store a lambda
    auto f_display_42 = { print_num(42); };
    f_display_42();

    // store a curried call
    alias curry!(print_num, 31337) f_display_31337;
    f_display_31337();

    // store a call to a member function
    auto f_add_display = (Foo foo, int i) { return foo.print_add(i); };
    auto foo = Foo(314159);
    f_add_display(foo, 1);
}

D has more features:

    // store a call to a member function on a particular object
    auto f_print_add_on_object = &foo.print_add;
    f_print_add_on_object(2);

There is also std.functional.toDelegate:

  http://dlang.org/phobos/std_functional.html#toDelegate

Ali

Reply via email to