将在抽象基础 class 上定义的向量的元素与具体派生的 class 相匹配

Match the elements of a vector defined over an abstract base class against a concrete derived class

假设我有以下抽象基 class:

class Base {
public:
    virtual void method() = 0;
    virtual const bool operator==(const Base& other) const = 0;
};

又具体派生了class.

class Derived : public Base {
public:
    int value_;
    Derived(int value) : value_(value) { }
    virtual void method() { }
    virtual const bool operator==(const Base& other) const {
        const Derived& derived = dynamic_cast<const Derived&>(other);
        return operator==(derived);
    }
    virtual const bool operator==(const Derived& other) const {
        return value_ == other.value_;
    }
};

使用 Google Mock,我现在想断言在基础 class 上定义的向量包含具体 class

的示例
TEST(ArrayContents, CompareAgainstDerivedClassElements) {
    Derived d1(0);
    Derived d2(0);
    std::vector<Base*> v { &d1 };
    ASSERT_THAT(v, Contains( Pointee(d2) ));
}

C++ 抱怨它无法创建 Eq 匹配器,因为 Base 是一个抽象 class.

error: no matching function for call to 'Eq'
note: candidate template ignored: substitution failure [with T = perseus::Base]: parameter type 'perseus::Base' is an abstract class

当我更改 Base 时,它不再抽象了:

class Base {
public:
    virtual void method() { }
    virtual const bool operator==(const Base& other) const { return false; }
};

C++ 在 dynamic_cast 表达式处抛出 std::bad_cast 异常。

Google Mock 可以这样断言吗?

事实证明,解决方案是使用 WhenDynamicCastTo 匹配器:

ASSERT_THAT(v, Contains( WhenDynamicCastTo<Derived*>(Pointee(d2)) ));

这样,我也不需要虚拟 operator== 方法。