我在shared_memory中有多索引容器
//Create hash
typedef boost::multi_index::multi_index_container<
My_Key,
My_Key_hash_indices,
bip::allocator<MyKey, bip::managed_shared_memory::segment_manager>
> MyGlobalHash;
我需要根据配置使用以下其中一项:
有没有办法在不创建两种类型的情况下执行此操作,例如为分配器创建包装类并为两种类型继承。
的更多代码答案 0 :(得分:1)
不,你不需要那个。快速静态断言了解到默认的段管理器类型是相同的:
static_assert(std::is_same<
bip::managed_shared_memory::segment_manager,
bip::managed_mapped_file::segment_manager>{}, "incompatible segments");
所以,你可以使用一个:
using SegmentManager = bip::managed_shared_memory::segment_manager;
<强> Live On Coliru 强>
#include <iostream>
#include <boost/interprocess/managed_shared_memory.hpp>
#include <boost/interprocess/managed_mapped_file.hpp>
#include <boost/interprocess/allocators/allocator.hpp>
namespace bip = boost::interprocess;
static_assert(std::is_same<
bip::managed_shared_memory::segment_manager,
bip::managed_mapped_file::segment_manager>{}, "incompatible segments");
using SegmentManager = bip::managed_shared_memory::segment_manager;
struct X {
int i = 0;
};
#include <boost/multi_index_container.hpp>
#include <boost/multi_index/member.hpp>
#include <boost/multi_index/ordered_index.hpp>
namespace bmi = boost::multi_index;
using Table = bmi::multi_index_container<X,
bmi::indexed_by< bmi::ordered_unique< bmi::tag<struct byI>, bmi::member<X, int, &X::i> > >,
bip::allocator<X, SegmentManager>
>;
void dump(Table const& t) {
std::cout << "table: ";
for(auto& x : t)
std::cout << x.i << "; ";
std::cout << std::endl;
}
void run_test(Table& table) {
dump(table);
if (table.empty()) {
table.insert({{1}, {2}, {3}, {4}});
} else {
table.insert({5});
}
dump(table);
table.erase(table.begin());
dump(table);
}
int main() {
{
bip::managed_shared_memory segment(bip::open_or_create, "msm", 10ul<<20);
run_test(*segment.template find_or_construct<Table>("name")(segment.get_segment_manager()));
}
{
bip::managed_mapped_file segment(bip::open_or_create, "mmf", 10ul<<20);
run_test(*segment.template find_or_construct<Table>("name")(segment.get_segment_manager()));
}
}
打印(在我的系统上),例如:
table: 2; 3; 4;
table: 2; 3; 4; 5;
table: 3; 4; 5;
table: 2; 3; 4;
table: 2; 3; 4; 5;
table: 3; 4; 5;