std::copy
と同様の機能を使用していると仮定しstd::remove_if
ます...フックを追加するための最良の方法は何ですか?特に、コピーのステータスをログに記録したいと思います。最後に、次と同等のものが必要です。
for(from begin to end iterator)
{
do the copy of the container;
cout << "." << flush;
}
しかし、使用std::copy
std::copy
と同様の機能を使用していると仮定しstd::remove_if
ます...フックを追加するための最良の方法は何ですか?特に、コピーのステータスをログに記録したいと思います。最後に、次と同等のものが必要です。
for(from begin to end iterator)
{
do the copy of the container;
cout << "." << flush;
}
しかし、使用std::copy
ほぼ1つの方法しかありません。コピーの観点からはまったく同じように動作する独自のイテレータで出力イテレータをラップしますが、internalyyもフックアクションを実行します。たとえば、これは一部のオペレーターの実装である可能性があります。
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()));
}
出力:
*
++
*
++
*
++
*
++
*
++