struct opCast to void* and back

Nrgyzer nrgyzer at gmail.com
Sun Apr 11 11:41:35 PDT 2010


Robert Clipsham Wrote:

> On 11/04/10 16:02, Nrgyzer wrote:
> > Because I call MyClass.cb by using an other class... for example the
> > Button-Class.
> ....
> > For example... I click on a button on my OpenGL-gui, then I simply
> > call the pressButton-method in my class Button which should call
> > MyClass.cb with callBackValue which can be a value, class, struct or
> > a similar datatype. To store different values/classes/structs... I
> > cast all to a void-pointer. In this case I can use the Button-class
> > in multiple situations.
> 
> By using templated classes you can remove the need for void*:
> ----
> struct MyStruct {
>           char[] structName;
>           public char[] toString() {
>                   return structName;
>           }
> }
> 
> class MyClass {
> 	public static Button!(MyStruct)[] loadButtons() {		
> 		Button!(MyStruct)[] buttons;	
> 		for (int i=0; i<  10; i++) {
> 			
> 			MyStruct curStruct = MyStruct();
> 			curStruct.structName = .toString(i);
> 
> 			buttons ~= new Button!(MyStruct)(cb, curStruct);
> 
> 		}
> 		return buttons;
> 	}
> 
>           public static void cb(MyStruct value) {
>                   writefln(value);
>           }
> }
> 
> class Button(T) {
>           private static void function(T) callBack;
>           private static T callBackValue;
> 	this(void function(T) cB, T cbValue) {
> 		callBack = cB;
> 		callBackValue = cbValue;
> 	}
> 
> 	public void pressButton() {
> 		// This should call MyClass.cb
> 		callBack(callBackValue);
> 	}
> }
> ----
> Of course this is more restrictive in some cases, such as if you wanted 
> an array of buttons with different types for their callback and 
> callbackValue, and it also adds template bloat if you have a lot of 
> different types for buttons. There should be a way around this, I can't 
> think of it off the top of my head though, perhaps someone else can.

I tried a bit with templates and classes - without success. I always get the following error: "Error: template instance Button!(myStruct) forward references template declaration Button(T)" when I try to create a Button array like this one:

private Button!(T)[];

That's exactly the same error message which was posted on http://www.digitalmars.com/d/archives/digitalmars/D/bugs/Issue_3834_New_forward_reference_in_templated_class_21207.html



More information about the Digitalmars-d mailing list