我很好奇以下为什么不编译:
#include <iostream>
#include <functional>
namespace Bar {
struct Foo {
int x;
};
} // Namespace
static bool operator==(const Bar::Foo& a, const Bar::Foo& b) {
return a.x == b.x;
}
int main() {
Bar::Foo a = { 0 };
Bar::Foo b = { 1 };
// The following line is OK
std::cout << (a == b) << std::endl;
// The following line is not OK
std::cout << std::equal_to<Bar::Foo>()(a, b) << std::endl;
}
在这种情况下编译器barfs:
[test]$ g++ --std=c++11 -o test test.cc
In file included from /usr/include/c++/4.8/string:48:0,
from /usr/include/c++/4.8/bits/locale_classes.h:40,
from /usr/include/c++/4.8/bits/ios_base.h:41,
from /usr/include/c++/4.8/ios:42,
from /usr/include/c++/4.8/ostream:38,
from /usr/include/c++/4.8/iostream:39,
from test.cc:1:
/usr/include/c++/4.8/bits/stl_function.h: In instantiation of ‘bool std::equal_to<_Tp>::operator()(const _Tp&, const _Tp&) const [with _Tp = Bar::Foo]’:
test.cc:18:46: required from here
/usr/include/c++/4.8/bits/stl_function.h:208:20: error: no match for ‘operator==’ (operand types are ‘const Bar::Foo’ and ‘const Bar::Foo’)
{ return __x == __y; }
^
/usr/include/c++/4.8/bits/stl_function.h:208:20: note: candidates are:
...
即使我尝试另一种变体,违规行也无法编译:
namespace Bar {
struct Foo {
int x;
bool operator==(const Foo& o) {
return x == o.x;
}
};
} // Namespace
但是,似乎以下 编译:
namespace Bar {
struct Foo {
int x;
};
static bool operator==(const Foo& a, const Foo& b) {
return a.x == b.x;
}
} // Namespace
这到底是怎么回事?
答案 0 :(得分:5)
在operator==
的包含之后声明了您的第一个<functional>
,因此operator==
的模板定义上下文中对std::equal_to<Bar::Foo>::operator()
的无限制查找将无法找到它。并且它不在Bar
中,Bar::Foo
唯一关联的命名空间,因此ADL也找不到它。
第二个成员版本barf因为equal_to
&#39; s operator()
通过const引用获取两个参数,但成员函数不是const
。
第三个版本有效,因为operator==
与Bar
位于同一名称空间中,因此可以通过ADL找到它。