std::复制钩子
std::copy hooks
假设我使用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()));
}
输出:*
++
*
++
*
++
*
++
*
++
相关文章:
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- std::ofstream 作为类成员删除复制构造函数?
- 使用 memcpy() 复制到 std::chrono::milliseconds 会给出错误 -Werror=clas
- 在什么条件下使用 std::memcpy 在对象之间复制是安全的?
- 使用赋值运算符复制 std::vector
- 复制STD :: sTD :: suolty_ptr带有多态性内容
- 在线程之间复制 std::vector 而不锁定
- 复制std ::功能多么昂贵
- 复制 std::vector,但将 lambda 应用于每个元素
- 使用 copy_if 复制 std::字符串(复制到另一个字符串中)
- 关于从第二个存储值_ty2秒复制std :: Map Iterator的数据的问题
- 为什么我们不能简单地复制 std::function
- C++ - 如何使用自己的类复制 std::固定语法
- 复制 std::function 构造函数的链接器错误
- 我是否应该复制std::函数,或者我可以总是引用它
- 复制std::列表中的垃圾
- c++复制std::string到char数组,不带null终止
- 复制std::vector:prefer赋值或std::copy
- 复制std::ofstream附加内容
- 无法使用统一初始化复制 std::vector<std::function<void ()>>。这是对的吗?