www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - Re: Sturcts with constructor (dmd1.x)

dsimcha Wrote:

 == Quote from Nrgyzer (nrgyzer googlemail.com)'s article
 Hello everyone,
 I currently try to create a structure with a construtor, but I always get the

 Error: Foo.this constructors are only for class definitions
 Error: constructor lisim.lsResult.lsResult.this special member functions not

 By compiling the follwing code:
 struct Foo {
     int len;
     bool len_done;
     const char* str;
     int length()
     {   if (!len_done)
         {   len = strlen(str);
 	    len_done = true;
 	return len;
     this(char* str) { this.str = str; }
 const Foo f = Foo("hello");
 I found that source on

source is for d2 and not for d1 but does d1 support similar operations (or is there no support for struct-constructors)?
 Thanks in advance :)

Struct constructors are D2 only. That said, you can fake them in D1 by overloading static opCall: struct Foo { uint field; static Foo opCall(SomeType someArgument) { Foo foo; // Do stuff. foo.field = someValue; return foo; } } auto foo = Foo(someArgument);

Thanks - that solution works great :)
Jan 12 2010