const Propagation

Julian Kranz via Digitalmars-d digitalmars-d at puremagic.com
Mon Dec 29 05:03:59 PST 2014


Hi all,

I've got a little problem regarding const. In fact, my problem 
originates from C++ where I've tried to implement a visitor that 
deals with both const and non-const objects. As this did not work 
out, I checked whether it would work in D. Unfortunately, I could 
not figure out how. Maybe someone can help.

Basically, I would like to propagate constness to a lambda 
function. Here's the example code:

import std.stdio;

class Hugo {
   public int x = 42;

   void blah(void function(Hugo h) f) {
     f(this);
   }
}

void main() {
     Hugo hugo = new Hugo();
     void function(Hugo h) f = function(Hugo h) {
       h.x = 99;
     };
     hugo.blah(f);

     const Hugo inge = hugo;
     void function(Hugo h) g = function(Hugo h) {
       writeln("foobar");
     };
     inge.blah(g);
}

This does not compile. The D compiler complains that I must not 
call a mutable method on a const object (inge). However, if I 
make the method const, I have to also make the parameter of the 
lambda const which results in the compiler rejecting the call 
"hugo.blah(f)" since this lambda actually modifies the object.

I hope you get what I want. I want to be able to call blah() on a 
const instance of Hugo with a lambda that does not modify its 
argument and otherwise call blah() with any function, even one 
that modifies the object. Is that possible?

Thank you very much!


More information about the Digitalmars-d mailing list