سؤال

Suppose you have the following code

namespace a{
  struct S{};
  //void f(int){}
}

namespace b{
  struct T{};
}


struct X{};

void f(X){}
void f(b::T){}
void f(a::S){}



namespace a{
  void g(){

    S s;b::T t; 
    X x;
    f(x);
    f(s);
    f(t);
  }

}

int main(){
  a::g();
}

if void f(int){} is defined in namespace a (line 3 is uncommented), it shadows the later definitions of void f(b::T){} and void f(a::S){}, but not void f(X){}. Why?

هل كانت مفيدة؟

المحلول

It shadows f(char) and f(int) will be called, since char can be implicitly casted to int. http://liveworkspace.org/code/8d7d4e0bc02fd44226921483a910a57b

EDIT.

There is function f(int) in namespace A. There is function f(A::S) in global namespace. We trying to call f(s) where s is A::S from function g, which is in namespace A, compiler finds, that function shall apply S (A::S), but there is no such function in namespace A, so compiler stops and give error. http://liveworkspace.org/code/5f989559d2609e57c8b7a655d5b1cebe

There is function f(B::T) in global namespace. Trying to find in namespace A (f(int)) and in namespace B (since arg-type is in namespace B), nothing finded, compiler stops. http://liveworkspace.org/code/4ebb0374b88b29126f85038026f5e263

There is function f(X) in global namespace, X is in global namespace, look at namespace A (f(int)) and in global namespace (find f(X)) - all is okay. http://liveworkspace.org/code/c9ef24db2b5355c4484aa99884601a1a

For more information please read par 3.4.2 of C++ standard (draft n3337). or, more simply http://en.wikipedia.org/wiki/Argument-dependent_name_lookup

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top