Search code examples
c++iteratorconstantscontainerscode-duplication

avoiding code duplication in const and non-const member functions


Well I'm currently refactoring a class I made quite a long time ago. The class is a container type.

Many functions can use advantage of the class structure, and are thus implemented as member functions. However it now seems to be a lot of function which seem "the same", ie a "find" function:

iterator find(ITEM)
const_iterator find(ITEM) const;
iterator find_if(ITEM, PRED)
const_iterator find_if(ITEM, PRED) const;

4 "functions" to describe nearly the same (and code is almost the same in each version). This becomes very tedious when updating the class, I have to make sure each version is upgraded. Is there a manner to handle these things better? Some other function in the class CAN possibly take 2 predicates, and that meant I suddenly had 8 functions to manage.

I tried calling the "non-constant version from the constant version" but that obviously doesn't work.

So how does one handle these things? Just bite the bullet and write it down?

EDIT: just to inform: my datastructure resembles a "tree". Each "object" contains the data (which the find searches) and a "list" with sub-trees. The find function works recursive over all subtrees of a tree (and sub-sub trees). - Just like one would expect when searching a tree.

As there isn't a clear "end" or "start" iterator to such a tree, using std::find doesn't yield the correct functionality.


Solution

  • Scott Meyers solved a similar problem in Item 3 of Effective C++ by calling the const version inside the non-const version and then casting the const result back to non-const:

    const_iterator find(const T& value) const
    {
        // actual implementation of find
    }
    
    iterator find(const T& value)
    {
        return const_cast<iterator>(static_cast<const container*>(this)->find(value));
    }