const and non-const member function

Frank Fischer frank.fischer at s2001.tu-chemnitz.de
Wed Jul 25 06:36:34 PDT 2007


Hi,

I'm just playing around with const in DMD 2.003 and I have a question.
In C++ it is possible to have a const and a non-const member function with
the same name and parameter types. It depends on the type of the reference
to the object which function is called:

class A {
public:
  int myfunc() { return 0; }
  int myfunc() const { return 1; }
};

A a;
a.myfunc(); // returns 0
const A& b = a;
b.myfunc(); // returns 1

Is something like this possible in D? 

Another example would be with different return-types:
class B {
  A a;
public:

  A& myfunc() { return a; }
  const A& myfunc() { return a; }
};

(of course, in D you don't need explicit references but the idea is the
same).

Furthermore, is it possible to overload opApply(...) so it can be called on
non-const objects and const objects, and the non-const variant has
read-write access:

foreach(ref x; obj) x = 1; // possible for non-const 'obj'
foreach(ref x; cast(const(Obj))obj) x = 1; // ERROR for const 'obj'
foreach(x; obj) writefln("%d", x); // Ok for both, const and non-const 'obj'

What would be the D-way of doing this? I need this access to provide the
correct member functions in some of my D-libraries I write, since I want to
have const-versions of my objects.

Thanks,
Frank



More information about the Digitalmars-d-learn mailing list