【发布时间】:2021-04-06 04:48:34
【问题描述】:
我有一个包含Collection<T> 映射的类,它被转换为void* 用于存储目的。
每个Collection<T> 可以保存一组ID,我想提供一些可变参数模板魔术来判断Collection<T> 的某些分组中是否存在某个ID。我只是不确定如何去做,在查看了一些示例之后,我缺少一些东西。
template<typename T>
class A {
public:
void add_id(int id) {
ids.emplace_back(id);
}
bool has(int id) {
return std::find(ids.begin(), ids.end(), id) != ids.end();
}
private:
std::vector<int> ids {};
};
class Collection {
public:
template<typename T>
void insert(T* item) {
items.insert({std::type_index(typeid(T)), reinterpret_cast<void*>(item)});
}
template<typename T>
bool contains(int id) {
return reinterpret_cast<T*>(items[std::type_index(typeid(T))])->has(id);
}
template<typename T>
bool does_have(int id) {
return contains<T>(id);
}
template<typename First, typename... Rest>
bool does_have(int id) {
return contains<First>(id) && does_have<Rest...>(id);
}
template<typename First, typename Second, typename... Rest>
bool does_have(int id) {
return contains<First>(id) && does_have<Second, Rest...>(id);
}
private:
std::map<std::type_index, void*> items;
};
这个想法是,在 Collection 类中存储一些项目之后,我可以做类似的事情
collection.does_have<A<int>, A<bool>, A<double>, A<float>>(15)
如果 ID 15 存在于所有 4 个中,则 does_have 返回 true。否则为假。
【问题讨论】: