void f() {} namespace test { void f(int) {} void g() { f(); } // error in gcc 6.2.0 } int main() { test::g(); }
用g -std = c 1z main.cpp编译它,输出如下:
06001
我的编译器是gcc 6.2.0.
为什么gcc会隐藏全局命名空间中的重载函数?这符合C标准吗?
解决方法
Why does gcc hide overloaded functions in the global namespace? Is this conforming to the C++ standards?
是.简而言之,您不能通过不同的范围重载功能.据的unqualified name lookup的规则,对于克()f()的的调用,该名称可以˚F命名空间内测试中找到,则该名称查找停止; overload resolution之后(基于找到的名称)发生.这意味着全局命名空间中的f()根本不会被考虑,即使它看起来更合适.
(强调我的)
For an unqualified name,that is a name that does not appear to the
right of a scope resolution operator ::,name lookup examines the
scopes as described below,until it finds at least one declaration
of any kind,at which time the lookup stops and no further scopes are
examined.In order to compile a function call,the compiler must first perform
name lookup,which,for functions,may involve argument-dependent
lookup,and for function templates may be followed by template
argument deduction. If these steps produce more than one candidate
function,then overload resolution is performed to select the function
that will actually be called.
您可以使用using将名称引入同一范围,即使它们成为实际的重载函数.
namespace test { using ::f; // introduce the name from global namespace void f(int) {} void g() { f(); } // fine }