我有一组多态类,例如:
class Apple {};
class Red : public Apple {};
class Green : public Apple {};
以及比较它们的免费功能:
bool operator==(const Apple&, const Apple&);
bool operator< (const Apple&, const Apple&);
我正在设计一个可复制的包装类,它允许我在 STL 映射中使用类Red
和Green
作为键,同时保留它们的多态行为。
template<typename Cat>
class Copy
{
public:
Copy(const Cat& inCat) : type(inCat.clone()) {}
~Copy() { delete type; }
Cat* operator->() { return type; }
Cat& operator*() { return *type; }
private:
Copy() : type(0) {}
Cat* type;
};
我希望该Copy<Apples>
类型尽可能可互换Apples
。还有一些函数我必须添加到上面的Copy
类中,但现在我正在为 开发一个免费函数operator==
,如下所示:
template<typename Cat>
bool operator==(const Copy<Cat>& copy, const Cat& e) {
return *copy == e;
}
这是我的测试代码的一部分:
Red red;
Copy<Apple> redCopy = red;
Copy<Apple> redCopy2 = redCopy;
assert(redCopy == Red());
但是编译器告诉我
../src/main.cpp:91: error: no match for ‘operator==’ in ‘redCopy == Red()’
如何让它识别上面的 operator==?我怀疑答案可能是在某处添加一些隐式转换代码,但我不确定该怎么做。