[LC++]code reuse in const and non-const methods
Dr Mark H Phillips
mark at austrics.com.au
Wed Oct 23 12:56:01 UTC 2002
On Wed, 2002-10-23 at 13:51, hursh wrote:
> Hi,
>
> I'm trying to find declaration incantation that will allow me to reuse
> the same implementation for a const and non-const method that return a
> reference to *this.
Why must they return a reference to *this? Couldn't you do a version
of neatThings() which is void, and use something else to give you *this?
>
> class Foo {
> // neat things
> Foo& neatThings(){
> // do neat things here
> return *this;
> }
>
> const Foo& neatThings() const{
> // do the same neat things
> return *this;
> }
> };
>
> If I declare it const I can't use the return value in non-const ways
> even if the instance is non-const. If I don't declare it const, I can't
> call it on const instances. (Have I got this wrong?)
I'm not sure whether your design is best, but leaving that aside for
now... What you could do is:
class Foo {
public:
Foo& neatThings() {
doStuff();
return *this;
}
const Foo& neatThings() const {
doStuff();
return *this;
}
private:
void doStuff() const {
// do your neat things here
}
};
Hope this helps.
Cheers,
Mark.
>
> I don't want to maintain the same code in two places if I don't have
> too. I don't want to use a macro. Templates just feel wrong here. I
> don't have it in the above example, but in my real world case the
> methods are virtual. Basically a draw routine. No changes happen to
> the object within the method(s), but it could be called in both consts
> and non-const contexts.
>
> Any ideas? Thanks,
> Dan
>
>
>
> _______________________________________________
> This is the Linux C++ Programming List
> : http://lists.linux.org.au/listinfo/tuxcpprogramming List
--
Dr Mark H Phillips
Research Analyst (Mathematician)
AUSTRICS - smarter scheduling solutions - www.austrics.com
Level 2, 50 Pirie Street, Adelaide SA 5000, Australia
Phone +61 8 8226 9850
Fax +61 8 8231 4821
Email mark at austrics.com.au
More information about the tuxCPProgramming
mailing list