std::复制钩子

std::copy hooks

本文关键字:复制 std      更新时间:2023-10-16

假设我使用std::copy的功能与std::remove_if相似,…添加钩子的最佳方式是什么?我特别想记录复制的状态。最后我想要一些等价的东西:

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

但使用std::copy

几乎只有一种方法:用你自己的迭代器包装输出迭代器,从copy的角度来看,它的行为完全相同,但内部也执行钩子动作。例如,这可能是某个操作符的实现:

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;
  }
};
构造函数中的

提供了实际的迭代器和std::function对象(或者是普通函数/某些接口实例,如果你的编译器没有std::function)。

您可以将迭代器包装到一个结构中,在其中放入钩子,例如:

#include<list>
#include<algorithm>
#include<numeric>
#include <iostream>
#include <vector>
#include <assert.h>
using namespace std;
template<typename T>
struct wrap_{
    T i;
    typedef typename T::value_type value_type;
    typedef typename T::difference_type difference_type;
    typedef typename T::iterator_category iterator_category;
    typedef typename T::pointer pointer;
    typedef typename T::reference reference;
    wrap_(T i) : i(i){}
    wrap_& operator++(){
        cout << "++" << endl;
        i++;
        return *this;
    }
    wrap_ operator++(int){ i++; return *this; }
    difference_type operator-( wrap_ j ){
        return i-j.i;
    }
    value_type& operator*(){
        cout << "*" << endl;    
        return *i;
    }
};
template<typename T>
wrap_<T> wrap( T i){
    return wrap_<T>(i);
}
int main(){
    vector<int> V(5);
    for (int i=0;i<V.size();i++) V[i]=i+1;
    list<int> L(V.size());
    copy( wrap( V.begin()), wrap( V.end() ), L.begin());
    assert(equal(V.begin(), V.end(), L.begin())); 
}
输出:

*
++
*
++
*
++
*
++
*
++