【发布时间】:2022-01-17 03:49:45
【问题描述】:
我正在尝试使用 lambdas 来找到一种方法来查找基类类型的向量中有多少特定的派生类。
std::vector<std::unique_ptr<Account>> openedAccounts;
int countCurrent = std::count_if(openedAccounts.begin(), openedAccounts.end(),
[](std::unique_ptr<Account> ptr) { return dynamic_cast<Current&>(*ptr) != nullptr; }); // I will call this for savings as well
帐户是基本抽象类,当前帐户是派生类。
我收到错误no operator != matches these operands".
但是,我认为动态转换可以返回一个空指针。
【问题讨论】:
-
您正在转换为引用,与指针类型进行比较。引用不能是
nullptr。 -
这里的问题是您正在尝试复制
unique_ptr。顾名思义,unique_ptr是独一无二的,你不能复制它。 Lambda 必须是[](const std::unique_ptr<Account>& ptr) -
@HattedRooster 那么有什么办法呢?
-
@MarekR 不是这样
-
只需投射到一个指针并从那里检查。
标签: c++ pointers polymorphism smart-pointers dynamic-cast