title: C++ functor to output iterator adapter
body: <p>Given a functor appropriate for use with <code>std::for_each</code> and friends:</p>
  
  <pre><code>template &lt;typename T&gt; struct Foo {
      void operator()(T const&amp; t) { ... }
  };
  
  std::for_each(v.begin(), v.end(), Foo&lt;Bar&gt;());
  </code></pre>
  
  <p>Is there some standard way to convert this into an output iterator appropriate for use with <code>std::copy</code> and friends?  (or the opposite adaptation)  Something like:</p>
  
  <pre><code>std::copy(v.begin(), v.end(), functor_output_iterator(Foo&lt;Bar&gt;()));
  </code></pre>
  
  <p>Which would call the functor each time a value is assigned to the iterator:</p>
  
  <pre><code>adapter(F f) : functor(f) { }
  adapter&amp; operator*()  { return *this; }
  operator=(T const&amp; t) { functor(t); }
  operator++()          { }
  ...
  </code></pre>
  
  <p>Or, alternatively:</p>
  
  <pre><code>std::for_each(..., some_adapter(std::ostream_iterator(std::cout)));
  </code></pre>
  
  <hr>
  
  <p>Background:</p>
  
  <p>I have a class that exposes a collection using an output iterator:</p>
  
  <pre><code>template &lt;typename It&gt; GetItems(It out) {
      MutexGuard guard(mutex);
      std::copy(items.begin(), items.end(), out);
  }
  </code></pre>
  
  <p>This allows callers to get access to the items without forcing them to use a specific container type and without messing around with locking or other internal details.</p>
  
  <p>e.g., to get only unique items:</p>
  
  <pre><code>std::set&lt;whatever&gt; set;
  obj-&gt;GetItems(std::inserter(set, set.end()));
  </code></pre>
  
  <p>This beats the hell out of:</p>
  
  <pre><code>ObjLock lock = obj-&gt;GetLock();
  for (int i = 0; i &lt; obj-&gt;GetItemCount(); ++i) {
      Item* item = obj-&gt;GetItem(i);
      ...
  </code></pre>
  
  <p>Now I also want to be able to aggregate these items, rather than copying them.  (See <a href="https://stackoverflow.com/questions/2216041">this question</a>).  Where I would normally do something like:</p>
  
  <pre><code>std::for_each(v.begin(), v.end(), Joiner&lt;Foo&gt;());
  </code></pre>
  
  <p>Now I could make two separate methods for the same data elements, one that calls <code>std::copy</code> and one that calls <code>std::for_each</code> but it would be nice to be able to define just one such method, using an iterator or a functor, and have callers be able to pass either functors or iterators to it, adapting them as necessary to the appropriate type.</p>
  
  <p>What I'm doing now is defining the aggregator in such a way that it can be used as either an output iterator or a functor, but this leads to unwanted complexity.</p>