www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - function literals cannot be class members


I have experienced that it becomes quite difficult to instantiate certain
template structs/classes as members of another class/struct, when
function/delegate need to be passed as a template parameter to the
instantiated templates. For example if I wish to instantiate a binary heap,
and I want to pass a complicated comparison function, the semantics force me
to make the heap instantiation inside a class function. This happens because
when the heap is instantiated as a class member and I try passing a delegate
literal as the comparison operator, the compiler construes the delegate
literal to be a class member which it does not allow.

For example, look at the following code. Since the delegate literal is
deemed to be class member, this code not allowed. This forces me to move the
BinaryHeap instance inside a member function like "bar" in the code. As a
result I loose the capability to access this heap instance from other
functions like frop, since it now is inside a function scope and is no
longer a member of the class object.

// file heap.d -- this code does not compile
import std.container;

class Foo {
  bool signed = false;
  BinaryHeap!(uint, delegate (uint a, uint b) {if(signed) a > b; else b >
a;}) heap;

  void bar () {/* uses heap */}
  void frop () {/* uses heap */}

void main() {
  Foo foo;

// end of file

Can not this limitation be overcome by creating a special local scope for
such delegate literals? Is something to this effect planned?

Or is there any obvious existing solution I am missing here?

- Puneet
Jul 16 2011