我有multi_index_container
看起来基本上是这样的:
struct MyStruct {
int a, b, c;
};
struct Tag1;
struct Tag2;
typedef multi_index_container<
MyStruct,
indexed_by<
hashed_non_unique<
tag<Tag1>,
composite_key<
MyStruct,
member<MyStruct, int, &MyStruct::a>,
member<MyStruct, int, &MyStruct::b>
>
>,
hashed_non_unique<
tag<Tag2>,
composite_key<
MyStruct,
member<MyStruct, int, &MyStruct::a>,
member<MyStruct, int, &MyStruct::b>,
member<MyStruct, int, &MyStruct::c>
>
>
>
> MyContainer;
我实例化这样一个容器并使用它的索引如下:
MyContainer c;
MyContainer::index<Tag1>::type& index1 = c.get<Tag1>;
MyContainer::index<Tag2>::type& index2 = c.get<Tag2>;
现在,在运行时,我想在两个索引中的一个上做equal_range
。实际使用哪个索引取决于当前配置。我想要完成的是这样的事情:
// Search in container
SomeType range;
if (useIndex1)
range = index1.equal_range(...);
else
range = index2.equal_range(...);
// Loop through range
for (auto i = range.first; i != range.second; ++i)
...
我不知道该怎么做。事实证明,index1.equal_range
的返回类型是一对与index2.equal_range
返回的迭代器不同的迭代器。两者有共同的基础类型吗?看看我的例子,SomeType
看起来会是什么样的?我不想在我的代码中为可能使用的每个索引重复for
循环。
答案 0 :(得分:2)
不是尝试使用范围进行类型擦除,而是将循环逻辑放入lambda并使用std :: for_each应用它:
#include <boost\multi_index_container.hpp>
#include <boost\multi_index\composite_key.hpp>
#include <boost\multi_index\member.hpp>
#include <boost\multi_index\hashed_index.hpp>
using namespace boost::multi_index;
struct MyStruct {
int a, b, c;
};
struct Tag1;
struct Tag2;
typedef multi_index_container
<
MyStruct
, indexed_by
<
hashed_non_unique
<
tag<Tag1>
, composite_key
<
MyStruct
, member<MyStruct, int, &MyStruct::a>
, member<MyStruct, int, &MyStruct::b>
>
>
, hashed_non_unique
<
tag<Tag2>
, composite_key
<
MyStruct
, member<MyStruct, int, &MyStruct::a>
, member<MyStruct, int, &MyStruct::b>
, member<MyStruct, int, &MyStruct::c>
>
>
>
> MyContainer;
int main()
{
MyContainer c;
MyContainer::index<Tag1>::type& index1 = c.get<Tag1>();
MyContainer::index<Tag2>::type& index2 = c.get<Tag2>();
//! Add some values
for (int i = 0; i < 10; ++i)
{
MyStruct s = { i, i * 2, i * 3 };
c.insert(s);
}
auto loop = [](const MyStruct& s){ std::cout << "{ " << s.a << ", " << s.b << ", " << s.c << " }" << std::endl; };
// Search in container
bool useIndex1 = true;
if (useIndex1)
{
auto range = std::make_pair(index1.begin(), index1.end());
std::for_each(range.first, range.second, loop);
}
else
{
auto range = std::make_pair(index1.begin(), index1.end());
std::for_each(range.first, range.second, loop);
}
// Loop through range
//for (auto i = range.first; i != range.second; ++i)
return 0;
}