c++ - Why does `using A::f` not work as expected? -
the next code rejected vc++ , clang.
why using a::f not work expected?
is there way hide names in given name space?
namespace { int f() { homecoming 1; } }; namespace b { int f() { homecoming 2; } }; using namespace a; using namespace b; using a::f; // want hide b::f , utilize a::f, how do? int main() { auto n = f(); // error : phone call 'f' ambiguous }
the standard specifies interpretation of using directive. emphasis mine:
a using-directive specifies names in nominated namespace can used in scope in using-directive appears after using-directive. during unqualified name lookup (3.4.1), names appear if declared in nearest enclosing namespace contains both using-directive , nominated namespace. [ note: in context, “contains” means “contains straight or indirectly”. — end note ]
(c++11 §7.3.4/2)
thus, after
using namespace a; using namespace b; an unqualified lookup name f finds a::f , b::f as though have been declared in global namespace. declaration using a::f introduces name f global namespace in same way (although differs in makes a::f fellow member of global namespace), redundant far unqualified lookup goes. point unqualified name lookup f finds both a::f , b::f in same declarative region.
solution?
int main() { using a::f; auto n = f(); // no longer ambiguous; finds a::f } the first place unqualified name lookup looks in block scope of main, find a::f, though a::f , b::f both found in enclosing namespace scope if searched.
c++ namespaces using
No comments:
Post a Comment