简体   繁体   English

C ++函数输出迭代器适配器

[英]C++ functor to output iterator adapter

Given a functor appropriate for use with std::for_each and friends: 给定一个适合与std::for_each和朋友一起使用的std::for_each函数:

template <typename T> struct Foo {
    void operator()(T const& t) { ... }
};

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

Is there some standard way to convert this into an output iterator appropriate for use with std::copy and friends? 有没有一些标准的方法将其转换为适合与std::copy和朋友一起使用的输出迭代器? (or the opposite adaptation) Something like: (或相反的改编)类似于:

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

Which would call the functor each time a value is assigned to the 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 exposes 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 get access to the items without forcing them to use a specific container type and without messing around with locking or other internal details. 这允许调用者访问项目,而不必强制他们使用特定的容器类型,也不会弄乱锁定或其他内部细节。

eg, to get only unique items: 例如,只获得独特的物品:

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

This beats the hell out of: 这打败了:

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 aggregate these items, rather than copying them. 现在我也希望能够聚合这些项目,而不是复制它们。 (See this question ). (见这个问题 )。 Where I would normally 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 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. 现在我可以为相同的数据元素创建两个单独的方法,一个调用std::copy ,另一个调用std::for_each但是能够使用迭代器或仿函数定义一个这样的方法会很好并让调用者能够将函子或迭代器传递给它,根据需要调整它们到适当的类型。

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. 我现在正在做的是以这样一种方式定义聚合器,它可以用作输出迭代器或仿函数,但这会导致不必要的复杂性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM