假设我有:
class A {
public:
operator ==(int int_val) { return (m_int_val == int_val); }
private:
int m_int_val;
};
然后我可以这样做:
bool my_func(const A &a) { return (a == 42); }
甚至:
bool my_func(const A *a) { return ((*a) == 42); }
到现在为止还挺好。但是假设我有:
std::list<A *> a_list;
我想做的事情如下:
auto it = std::find(a_list.begin(), a_list.end(), 42);
然后编译器抱怨,因为你无法将指针A与整数进行比较。
我的问题不是如何用std::find_if
来解决这个问题(只是为了抢先一步)。我的问题是我可以为指针A定义一个等价运算符,使得上面的std::find
操作有效,如果是,如何?
我问,因为我想更好地理解C ++。
您的运算符相当于重载1,2:
operator==(A const&, int);
所以你想重载这个:
operator==(A const*, int);
...但是you cannot会重载运算符,除非其参数之一具有用户定义的类型 - 并且指向任何类型的指针(例如,A const*
)都不是用户定义的。
这里最简单的方法是使用std::find_if
而不是std::find
并提供lambda:
auto it = std::find_if(std::begin(a_list), std::end(a_list),
[](auto const* pa) { return *pa == 42; });
1你实际上正在超载operator==(A&, int)
,因为你没有const
限定方法(这应该是bool operator==(int int_val) const { ... }
)。
2对于此类运算符,通常会重载非成员函数而不是成员函数。