我很难综合我的问题,我不确定标题是否很好地总结了它:/
我试图在一个结构中保留一个多态容器的映射,以便拥有一个漂亮的平面对象数组。
我的问题是我想对包含的对象应用一个函数,但仅限于从指定的 Base 类型派生的对象。下面是我要实现的目标的精简版本。
struct BaseStock {};
template <typename ContainedType>
struct Stock : BaseStock {
std::vector<ContainedType> container;
};
struct Store {
std::unordered_map<std::type_index, std::unique_ptr<BaseStock>> stocks;
template <typename Base>
void something() {
for (auto& pair: stocks) {
// Here, do somehting only if pair.second's
// contained type derives from Base
}
}
};
我试图通过返回 void*
来访问 BaseStock
中包含的元素,但是不可能从中dynamic_cast
,因此不允许类型检查。 stocks
映射保留 Stock 所含类型的 type_index
,但也无法从中检索层次结构信息。
允许 BaseStock
返回可以检查的内容似乎是最接近的解决方案,但这意味着强制 ContainedType
始终派生自某些内容(这一点也不差,但我喜欢容器的想法,它不会对您使用的类型施加限制)
非常感谢您的帮助!
最佳答案
我认为这可以满足您的需求,请随时要求对您在评论中没有得到的内容进行更详细的解释。
#include <vector>
#include <iostream>
#include <unordered_map>
#include <typeindex>
#include <memory>
struct BaseStock {};
template <typename ContainedType>
struct Stock : BaseStock {
std::vector<ContainedType> container;
};
struct Store {
std::unordered_map<std::type_index, std::unique_ptr<BaseStock>> stocks;
template <typename Base>
void something() {
for (auto& pair: stocks) {
if (typeid(pair.first) != typeid(Base)) {
std::cout << "Checking via typeid.\n";
}
}
}
};
template<typename BaseType, typename DerivedType = BaseType>
void InsertIntoStore(Store* store) {
store->stocks[typeid(BaseType)] =
std::unique_ptr<BaseType>(std::make_unique<DerivedType>());
}
int main() {
Store store;
// Put two things into the map.
InsertIntoStore<BaseStock, Stock<int>>(&store);
InsertIntoStore<BaseStock>(&store);
// But only get one output.
store.something<BaseStock>();
}
关于c++ - 将函数应用于包含的对象,前提是它们派生自基类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40452297/