我在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;
我需要根据配置使用以下之一:
有没有一种方法可以同时创建两种类型,例如为分配器创建包装器类并为两种类型继承。
http://coliru.stacked-crooked.com/a/09ea79752512fad8上的更多代码
最佳答案
不,您不需要那。快速静态断言得知默认的段管理器类型相同:
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;
关于c++ - 将进程间包装器 boost 为分配器,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50586904/