仅当其类型匹配时,如何在std :: vector上添加元素

How to add elements on a std::vector only if their type matches

本文关键字:std vector 元素 添加 类型      更新时间:2023-10-16

我有一个基类fruit和子类orangesapples。两个子类过载operator+,因此我知道如何概括橙色或苹果。现在,我有一个对基类std::vector<std::reference_wrapper<fruit>>的参考文献,我想知道该向量中存储了多少个苹果和橘子,我该如何实现?

#include <vector>
#include <functional>
#include <typeinfo>
#include <algorithm>
struct fruit { virtual ~fruit() = default; };
struct apple : fruit {};
struct orange : fruit {};

auto count_oranges(std::vector<std::reference_wrapper<fruit>> const& vec) -> std::size_t
{
    return std::count_if(begin(vec), end(vec), [](auto&& ref)
    {
        return typeid(ref.get()) == typeid(orange);
    });
}