C ++非限定查找

时间:2015-07-12 08:29:40

标签: c++ argument-dependent-lookup name-lookup unqualified-name

我有以下代码:

//mystd plays a role of the std namespace
//which does not allow any new overloads in it
//so we define one in the global namespace
namespace mystd {

template<typename T>
struct A {};

}

//if one uncomment this, everything works as designed
//int f(const mystd::A<int>& v);

//this some namespace which is supposed to be the main one
namespace a {

template<typename T>
int f(const T& v) {
  return 0;
}

template<typename T>
int operator-(const T& v) {
  return 0;
}

}

//this should be different from ::a
//so that `using namespace a;` would import global functions 
//as well as all functions from namespace a, since 
//the global namespace is the nearest common namespace
//see http://www.open-std.org/jtc1/sc22/open/n2356/dcl.html#namespace.udir 
namespace b {

template<typename T>
int Call(const T& v) {
  using namespace ::a;
  return -v + f(v);
}

}

int operator-(const mystd::A<int>&) {
  return 1;
}
int f(const mystd::A<int>&) {
  return 2;
}

int main() {
  //why this returns 1, not 3?
  //what is the difference between operator-() & f()?
  return b::Call(mystd::A<int>());
}

这个想法是模仿gtest运算符的行为&lt;&lt; &安培; PrintTo,因此可以重载某些std类的行为,这是不能通过ADL完成的,因为不允许向std命名空间添加任何内容。但是,如果我尝试使用通常的函数f(),那么f(mystd::A())的重载被认为定义太晚(如果有人评论gcc给出的f()的模板定义note: ‘int f(const mystd::A<int>&)’ declared here, later in the translation unit

问题是为什么operator-()f()的行为不同?

0 个答案:

没有答案