【发布时间】:2017-06-13 07:11:30
【问题描述】:
我正在尝试将 std::find 与两种不同的类型一起使用,但提供了必要的布尔运算符。
class FooDetails
{
public:
FooDetails(int size = 5)
: m_size(size) { /* empty */ }
bool operator<(const FooDetails& other) const { return m_size < other.m_size; }
bool operator==(const FooDetails& other) const { return m_size == other.m_size; }
private:
int m_size;
};
class Foo
{
public:
Foo(int size)
: m_details(size) { /* empty */}
bool operator==(const Foo& other) const { return m_details == other.m_details; }
bool operator==(const FooDetails& other) const {return m_details == other; }
bool operator<(const Foo& other) const { return m_details < other.m_details; }
bool operator<(const FooDetails& other) const { return m_details < other; }
FooDetails m_details;
};
bool operator==(const FooDetails& lhs, const Foo& rhs) { return lhs == rhs.m_details; }
bool operator==(const Foo& lhs, const FooDetails& rhs) {return lhs.m_details == rhs; }
bool operator<(const FooDetails& lhs, const Foo& rhs) { return lhs < rhs.m_details; }
bool operator<(const Foo& lhs, const FooDetails& rhs) { return lhs.m_details < rhs; }
int main() {
std::vector<Foo> haystack = { FooDetails(5), FooDetails(6), FooDetails(7) };
FooDetails needle(6);
std::find(haystack.begin(), haystack.end(), needle);
return 0;
}
由于 std::find 使用 operator== 我希望这可以工作,因为提供了所有必要的功能。但是,这不会编译。为什么会这样,我该如何解决? 我知道我可以使用 std::find_if,但我认为这有点慢,即使不是,我也想知道为什么 std::find 不起作用。
【问题讨论】:
-
那么究竟是什么的错误是什么?在哪一行。
-
你有两次
operator==,所以编译器不知道选择哪一个。注释掉一个就行了。下一个错误是初始化类型为Foo的干草堆,类型为FooDetails
标签: c++ c++11 stl operator-overloading