boost multi_index - 如果元素类型仅支持移动语义,如何遍历它?

boost multi_index - how to iterate through it if element type supports move-semantic only?

本文关键字:何遍历 遍历 语义 移动 index multi 如果 元素 支持 类型 boost      更新时间:2023-10-16
typedef boost::multi_index_container<foo, ...
struct foo {
...
std::unique_ptr<Bar> bar; // requires move-semantic only
foo() { bar = std::make_unique<Bar>(); }
foo(foo&&) = default;
};

我对push_back没有任何问题 - 只是使用push_back(std::move(...)).

此外,以下方面没有问题:

auto it = container.get<...>().find(...);
container.erase(it);

但我还需要迭代容器的所有元素。我做:

for (auto it = container.begin(); auto it = container.end(); ++it) {
some_foo(*it); // For instance, another_container_of_same_type.push_back(*it) - to merge 2 containers
}

或者,在特殊情况下:

for (auto it = container.begin(); auto it = container.end(); ++it) {
// some logics
another_container_of_same_type.push_back(*it); //another container defined same as first one
// some logics
}

而且它不编译!

我试过了:

some_foo(std::move(*it))
some_foo(std::move(it))
some_foo(it)
some_foo(*it)

不编译。它想要复制构造函数或移动...

警告:不,它不是简单地合并两个容器,我在合并中使用我的自定义逻辑,也使用迭代而不仅仅是为了合并。

您没有显示some_foo的声明,但可能您没有通过引用获取参数。

这里有一个简单的、自包含的例子,应该能让你开始。

住在科利鲁

#include <boost/multi_index_container.hpp>
#include <boost/multi_index/sequenced_index.hpp>
// move-only
struct foo {
foo()           = default;
foo(foo&&)      = default;
foo(foo const&) = delete;
foo& operator=(foo&&)      = default;
foo& operator=(foo const&) = delete;
};
namespace bmi = boost::multi_index;
using foos = bmi::multi_index_container<foo, bmi::indexed_by<bmi::sequenced<> > >;
void some_foo(foo const&) {}
int main() {
foos c;
for (auto& el : c) {
some_foo(el);
}
}

编译正常。