Taking a function or delegate as argument.
Jacob Carlborg
doob at me.com
Tue Jan 10 11:56:04 PST 2012
On 2012-01-10 20:24, bls wrote:
> On 01/10/2012 06:53 AM, Jacob Carlborg wrote:
>> On 2012-01-10 14:48, simendsjo wrote:
>>> On 10.01.2012 14:43, Mike Parker wrote:
>>>> On 1/10/2012 10:05 PM, simendsjo wrote:
>>>>> If I want to have a method taking a callback function, I have to
>>>>> specify
>>>>> if it should take a function or delegate even if I don't really care.
>>>>> What's the best way to accept either? I cannot see any wrapper for
>>>>> something like this in std.typecons.
>>>>
>>>> The simple way:
>>>>
>>>> void callback(int i, void delegate(int) dg)
>>>> {
>>>> dg(i);
>>>> }
>>>>
>>>> void callback(int i, void function(int) fn)
>>>> {
>>>> void wrap(int j)
>>>> {
>>>> function(j);
>>>> }
>>>> callback(i, &wrap);
>>>> }
>>>
>>> Yeah, but a bit tedious.. I found toDelegate:
>>> http://dlang.org/phobos/std_functional.html#toDelegate
>>
>> Or make it a template parameter and check if it's callable using
>> std.traits.isCallable.
>>
> What's wrong with toDelegate ? Seems to be pretty handy.
>
> //simple snip
> import std.functional;
>
> int main()
> {
> int delegate( int i) dg;
> alias dg callback;
> callback = toDelegate(&test);
> writeln( callback( 12 ) );
> readln();
>
> return 0;
> }
>
> int test(int i) { return 30 +i;}
A template parameter with a template constraint will accept any callable
type. Function pointer, delegate, struct/class overloading the call
operator and so on.
--
/Jacob Carlborg
More information about the Digitalmars-d-learn
mailing list