What about:
template<typename IN, typename OUT> OUT BigChunk(IN self, int index) { // big, non-trivial chunk of code... return something; } struct FooBar { Something &getSomething(int index) { return BigChunk<FooBar*, Something&>(this,index); } const Something &getSomething(int index) const { return BigChunk<const FooBar*, const Something&>(this,index); } };
Obviously, you will still have duplicate object code, but no duplication of source code. Unlike the const_cast approach, the compiler checks for your const validity for both versions of the method.
You probably need to declare two interesting instances of BigChunk as friends in this class. This is a good use of a friend, since the friendβs functions are hidden next to each other, so there is no risk of unconditional communication (ooh-er!). But I will not try to use the syntax for this right now. Feel free to add.
Most likely, BigChunk should respect itself, and in this case the above determination procedure will not work very well, and some forward declarations will be required to sort it.
In addition, to avoid the BigChunk multiple search in the header and making a decision about creating an instance and invoking it even if it is morally closed, you can move the entire batch to the cpp file for FooBar. In an anonymous namespace. With an internal connection. And the sign saying "beware of the leopard."
Steve Jessop May 13 '09 at 16:14 2009-05-13 16:14
source share