C++中如何将含派生类的std::map传入函数?
问题:如何让函数接受含基类指针的std::map并处理子类类型?
我希望编写一个能接受包含基类指针的std::map的函数,但尝试后无法正常运行。以下是简化示例代码:
struct Entity { int i; Entity(const int i_) : i(i_) {} virtual ~Entity() {} }; struct A : public Entity { bool a; A(const int i_, const bool a_) : Entity(i_), a(a_) {} }; void efunc(const std::map<int, std::shared_ptr<Entity>>& m) { for (auto& it : m) { std::cout << it.second->i << std::endl; } } int main() { std::map<int, std::shared_ptr<A>> aMap; std::shared_ptr<A> myA = std::make_shared<A>(1, true); aMap.insert({myA->i, myA}); // efunc(aMap); // 无法运行 }
显然直接传递该map不可行,请问:
- 如何解决此问题?
- 如何检测map中的子类类型以执行特定代码?
更新1:使用模板似乎可以解决问题,当前代码如下:
template <class T> void tfunc(const std::map<int, std::shared_ptr<T>>& m) { for (auto& it : m) { std::cout << it.second->i << std::endl; } }
但这样会丢失IntelliSense支持,且我不理解编译器为何不报错。我觉得concept或许能帮助约束T继承自Entity,但目前暂不需要深入。
更新2:以下是使用concept确保模板包含成员i的代码:
template <class T> concept hasI = requires(T a) { a.i; }; template <class T> concept inheritsEntity = std::derived_from<T, Entity>; template <hasI T> /// 备选写法:template<inheritsEntity T> void tfunc(const std::map<int, std::shared_ptr<T>>& m) { for (auto& it : m) { std::cout << it.second->i << std::endl; } }
内容的提问来源于stack exchange,提问作者Markstar
相关产品推荐
相关产品推荐

