September 18, 2014
I'm trying to write a struct with delegate member variables that I want to default to do-nothing stubs (rather than null function pointers that will crash when called), but it appears that such a thing is not supported. I've tried all sorts of things, but none of them worked:

	struct S {
		void delegate(dchar) dg = (dchar) {};
		// test.d(2): Error: delegate test.S.__lambda2 cannot be class members
	}

	struct S {
		void delegate(dchar) dg = {};
		// test.d(2): Error: delegate test.S.__dgliteral2 cannot be class members
	}

	void delegate(dchar) stub = (dchar) {};
	struct S {
		void delegate(dchar) dg = stub;
		// test.d(3): Error: static variable stub cannot be read at compile time
	}

	immutable(void delegate(dchar)) stub = (dchar) {};
	// test.d(1): Error: non-constant nested delegate literal expression __lambda4
	// test.d(1): Error: non-constant nested delegate literal expression __lambda4
	// [Why the repeated message, and what on earth does this mean
	// anyway?!]
	struct S {
		void delegate(dchar) dg = stub;
	}

Is there a way to achieve this? If not, why not? Would it be worth filing an enhancement request for this?

Note that the lack of argumentless struct ctors exacerbates this problem, since there is no way to work around the lack of language support here.


T

-- 
Береги платье снову, а здоровье смолоду.
September 18, 2014
On Thursday, 18 September 2014 at 17:49:34 UTC, H. S. Teoh via
Digitalmars-d wrote:
> I'm trying to write a struct with delegate member variables that I want
> to default to do-nothing stubs (rather than null function pointers that
> will crash when called), but it appears that such a thing is not
> supported.
[...]
> Is there a way to achieve this?

Here's a hack:

struct S
{
     union
     {
         struct
         {
             void* contextPtr;
             void function(dchar, void* contextPtr) funcPtr = (a,
ignored) {writeln(a);};
         }
         void delegate(dchar) dg;
     }
}