www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - Initializing a delegate member

reply "Lionello Lunesu" <lionello.lunesu crystalinter.remove.com> writes:
Am I missing something... again?

import std.c.stdio;

class compiles {
 this() { _putc = &putc_ascii; }
 void delegate(int) _putc;
 void putc_ascii(int c) { putchar(c); }
};

class does_not_compile {
 void delegate(int) _putc = &putc_ascii;
 void putc_ascii(int c) { putchar(c); }
};

int main( char[][]arg )
{
 // keep linker happy
 return 0;
}

-- 
L.

-- Get the root certificate at https://www.cacert.org/ 
Dec 09 2004
parent reply Russ Lewis <spamhole-2001-07-16 deming-os.org> writes:
Lionello Lunesu wrote:
 Am I missing something... again?
 
 import std.c.stdio;
 
 class compiles {
  this() { _putc = &putc_ascii; }
  void delegate(int) _putc;
  void putc_ascii(int c) { putchar(c); }
 };
 
 class does_not_compile {
  void delegate(int) _putc = &putc_ascii;
  void putc_ascii(int c) { putchar(c); }
 };
 
 int main( char[][]arg )
 {
  // keep linker happy
  return 0;
 }
The thing that you have to remember is that a delegate actually has 2 pointers embedded in it: a function pointer, and a pointer to the object. Thus, if you create 2 copies of the class "compiles", they will have different "_putc" members. Since the value of the delegate varies from object to object, you can't initialize it statically.
Dec 09 2004
parent "Lionello Lunesu" <lionello.lunesu crystalinter.remove.com> writes:
Hi..

 The thing that you have to remember is that a delegate actually has 2 
 pointers embedded in it: a function pointer, and a pointer to the object. 
 Thus, if you create 2 copies of the class "compiles", they will have 
 different "_putc" members.
Yes, I missed that. However, the _putc is the same for both (same code for both), but the 'parameter' (==this) is different for both instances.
 Since the value of the delegate varies from object to object, you can't 
 initialize it statically.
Yes, makes sense. I kind of figured that writing "class t { int a=0; };" would add "a=0;" to a generated constructor and that anything that's valid in a constructor could be written using the same syntax, but now I know that only 'statically evaluatable statements' (:-S) can be written liked that. Thanks for the reply.. Lionello.
Dec 10 2004