[LC++]code reuse in const and non-const methods

hursh hursh at infonet.isl.net
Wed Oct 23 12:22:01 UTC 2002


	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.

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 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,

More information about the tuxCPProgramming mailing list