C ++ functor to output an iteration adapter

Given a functor suitable for use with std::for_each and friends:

 template <typename T> struct Foo { void operator()(T const& t) { ... } }; std::for_each(v.begin(), v.end(), Foo<Bar>()); 

Is there a standard way to convert this to an output iterator suitable for use with std::copy and friends? (or vice versa) Something like:

 std::copy(v.begin(), v.end(), functor_output_iterator(Foo<Bar>())); 

which will call a functor every time a value is assigned to an iterator:

 adapter(F f) : functor(f) { } adapter& operator*() { return *this; } operator=(T const& t) { functor(t); } operator++() { } ... 

Or alternatively:

 std::for_each(..., some_adapter(std::ostream_iterator(std::cout))); 

Background:

I have a class that provides a collection using an output iterator:

 template <typename It> GetItems(It out) { MutexGuard guard(mutex); std::copy(items.begin(), items.end(), out); } 

This allows callers to access the items without forcing them to use a particular type of container and without interfering with the lock or other internal details.

For example, to get only unique items:

 std::set<whatever> set; obj->GetItems(std::inserter(set, set.end())); 

It beats the hell:

 ObjLock lock = obj->GetLock(); for (int i = 0; i < obj->GetItemCount(); ++i) { Item* item = obj->GetItem(i); ... 

Now I also want to be able to collect these elements, not copy them. (See this question .) Where would I usually do something like:

 std::for_each(v.begin(), v.end(), Joiner<Foo>()); 

Now I could make two separate methods for the same data elements: one that calls std::copy and one that calls std::for_each , but it would be nice to be able to define only one such method using an iterator or functor , and have callers able to pass either functors or iterators to it, adapting them as necessary to the appropriate type.

Now I define the aggregator in such a way that it can be used as an output iterator or functor, but this leads to undesirable complexity.

+7
c ++ iterator functor stl templates
source share
1 answer
+5
source share

All Articles