Search code examples
c++stdstl-algorithm

std::copy hooks


Suppose I'm using std::copy of similar function as std::remove_if, ... what it the best way to add an hook? In particular I want to log the status of the copying. At the end I want something equivalent to:

for(from begin to end iterator)
{
   do the copy of the container;
   cout << "." << flush;
}

but using std::copy


Solution

  • there's pretty much only one way: wrapping the output iterator with your own iterator that behaves exactly the same from copy's point of view, but internalyy also does the hook action. For example, this could be some operator's implementation:

    template< class T, bool constcv >
    class HookingIterator : public std::iterator< std::forward_iterator_tag, .... >
    {
    public:
      reference operator* ()
      {
        dereference_hook();
        return *actual_iterator_member;
      }
    
      this_type& operator ++ ()
      {
        increment_hook();
        ++actual_iterator_member;
        return *this;
      }
    };
    

    in the constructor supply the actual iterator, and std::function objects (or plain functions/some interface instances if your compiler doesn't have std::function).