On Monday, 29 December 2014 at 13:20:39 UTC, Julian Kranz wrote:
Thank you for your answer. This kind of thing also works for
C++, but that would mean that I would implement the whole
visitor twice - one const and one non-const version. Is that
really the only way? Can't I tell the D compiler that "the
argument of that lambda shares the const-ness of the current
object"?
D offers "inout"; this actually aims into the right directing,
but I guess it does not help here.
Is there any "static if"-something construct to check the
const-ness of an object?
There's a pattern I suggested before[1] that I'd like to mention
in addition to the template solutions Steven Schveighoffer and
Daniel Kozak gave:
Call the non-const overload from the const overload and cast
accordingly.
In your case:
void blah(void function(Hugo h) f) {
f(this);
}
void blah(void function(const Hugo h) f) const {
(cast(Hugo) this).blah(cast(void function(Hugo)) f);
}
This is safe as long as the non-const overload does not mutate
the object when f doesn't. BUT you have to make sure of that
yourself; the compiler can't help anymore.
[1]
http://stackoverflow.com/questions/22442031/how-to-make-a-template-function-const-if-the-template-is-true/22442425#22442425