Initializing a table of delegates with no-op stubs

Steven Schveighoffer schveiguy at gmail.com
Sat Jan 11 14:51:24 UTC 2020


On 1/11/20 4:40 AM, Rainer Schuetze wrote:
> 
> 
> On 09/01/2020 23:02, H. S. Teoh wrote:
>> void dummy(int) {}
>> 	struct S {
>> 		void function(int) f1 = &dummy; // OK
>>
>> 		// But it doesn't work with delegates, no way, no how:
>> 		void delegate(int) dg1 = &dummy; // NG
>> 		void delegate(int) dg2 = (int) {}; // NG
>> 		void delegate(int) dg3 = (int) => dummy(0); // NG
>> 	}
>>
> [...]
>> Am I missing something obvious??
>>
> 
> This seems to work:
> 
> void noop(int) {}
> 
> enum void delegate(int) dg_noop = (int x){ noop(x); };

No need for the function call

enum void delegate(int) dg_noop = (int x) {};

> 
> struct S
> {
>      void delegate(int) dg = dg_noop;
> }
> 

OK, so I think what is happening here is that a delegate defined inside 
a struct is going to use a struct `this` reference as the context 
pointer, and I get a weird message (why didn't you show this in the 
first place?): Error: delegate onlineapp.S.__lambda2 cannot be struct 
members

It could be a possibility that if you use a delegate as an initializer 
outside a member function context, then it becomes like a global delegate?

In any case, here is a solution that works and is pretty reasonable:

enum void delegate(T) dummydg(T...) = (T params) {};

struct S
{
     void delegate(int) dg = dummydg!int;
     void delegate(string, int) dg2 = dummydg!(string, int);
}

void main()
{
     S s;
     s.dg(1);
     s.dg2("hi", 1);
}

-Steve


More information about the Digitalmars-d mailing list