gpt4 book ai didi

c++ - 模板元编程如何专注于集合

转载 作者:行者123 更新时间:2023-11-30 05:32:07 26 4
gpt4 key购买 nike

我创建了以下 UtlSharedIPCWrapper 模板类来访问放置在进程间内存中的用户定义类型。

通常此类与简单类型一起使用,例如:

// construct a FaultReport - default to no faults
auto faultWrapper = managed_shm.construct<
UtlSharedIPCWrapper<uint64_t>>("FaultReport")(0);

这很好用,但是我最近需要使用 boost 共享内存映射集合(boost::interprocess::map)作为模板参数),如:

using char_allocator = boost::interprocess::managed_shared_memory::allocator<char>::type;
using shm_string = boost::interprocess::basic_string<char, std::char_traits<char>, char_allocator>;
using KeyType = shm_string;
using ValueType = std::pair<const KeyType, shm_string>;
using ShmemAllocator = boost::interprocess::allocator<ValueType, boost::interprocess::managed_shared_memory::segment_manager>;
using SharedMemoryMap = boost::interprocess::map<shm_string, shm_string, std::less<KeyType>, ShmemAllocator>;

...

// create a new shared memory segment 2K size
managed_shared_memory managed_shm(open_only, "sharedmemname");

//Initialize the shared memory STL-compatible allocator
ShmemAllocator alloc(managed_shm.get_segment_manager());

auto pSharedNVPairs = managed_shm.find<UtlSharedIPCWrapper<
SharedMemoryMap>>("NameValuePairs").first;

我的问题是如何更改下面的模板类定义以将 collection::value 类型作为参数传递,而不是通过 pSharedNVPairs->getSharedData() 更新临时映射并通过 pSharedNVPairs->setSharedData(*pSharedNVPairs) 再次将其写回共享内存。我知道这对于不是集合的类型会有所不同,因此必须执行一些模板元编程魔术,如果等,则选择性启用,但我想在我的类中添加一个方法,类似于

// I don't know the correct signature here
void setSharedDataValue(const T::value_type& rSharedDataValue) {
boost::interprocess::scoped_lock<upgradable_mutex_type> lock(mMutex);
... not sure what to do here to update the collection
}

template<typename T>
struct UtlSharedIPCWrapper {
private:
using upgradable_mutex_type = boost::interprocess::interprocess_upgradable_mutex;

mutable upgradable_mutex_type mMutex;
/*volatile*/ T mSharedData;
public:
// explicit constructor used to initialize directly from existing memory
explicit UtlSharedIPCWrapper(const T& rInitialValue)
: mSharedData(rInitialValue)
{}

T getSharedData() const {
boost::interprocess::sharable_lock<upgradable_mutex_type> lock(mMutex);
return mSharedData;
}

void setSharedData(const T& rSharedData) {
boost::interprocess::scoped_lock<upgradable_mutex_type> lock(mMutex);
// update the shared data copy mapped - scoped locked used if exception thrown
// a bit like the lock guard we normally use
this->mSharedData = rSharedData;
}
};

最佳答案

为什么不只是

// I don't know the correct signature here
void setSharedDataValue(const typename T::value_type& rSharedDataValue) {
boost::interprocess::scoped_lock<upgradable_mutex_type> lock(mMutex);
mSharedData.insert(rSharedDataValue);
}

关于c++ - 模板元编程如何专注于集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35258924/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com