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

template meta-programming how to specialize on a collection

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

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

// 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;

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

// 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);
}