You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 14:35:51