Overloading methods by constness?

Craig Black cblack at ara.com
Wed Aug 22 12:20:19 PDT 2007


Perhaps this should be posted as a bug?

"Nathan Reed" <nathaniel.reed at gmail.com> wrote in message 
news:faga07$hj9$1 at digitalmars.com...
> Hello,
>
> In C++, you can overload methods by the constness of the method itself:
>
> class Foo
> {
> void bar (); // #1
> void bar () const; // #2
> }
> ...
> Foo f; f.bar(); // calls #1
> const Foo g; g.bar(); // calls #2
>
> I am wondering if there is any way to get similiar functionality in D? I 
> have tried the following:
>
> class Foo
> {
> void bar () { ... }
> const void bar () { ... }
> }
>
> but get a compiler error that the "bar"s conflict.
>
> Why would I want to do this, you might ask?  Well, I would like to use 
> this to write a pair of opSlice methods.  With built-in arrays, you can do 
> this:
>
> char[] str = "Hello, world".dup;
> char[] substr = str[0..5];
>
> const(char)[] str2 = "Hello, world";
> const(char)[] substr2 = str2[0..5];
> char[] substr3 = str2[0..5]; // fails
>
> i.e., the slice returns either a char[] or a const(char)[] depending on 
> the constness of the array.  However, I cannot see how to make my own 
> classes do the same thing, unless I can overload opSlice by constness.
>
> Thanks,
> Nathan Reed 




More information about the Digitalmars-d-learn mailing list