异常C ++ [Bug]? [英] Exceptional C++[Bug]?

查看:137
本文介绍了异常C ++ [Bug]?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在阅读Herb Sutter的 Exceptional C ++ 。到达第32项

I have been reading Exceptional C++ by Herb Sutter. On reaching Item 32

我找到了以下

 namespace A 
 {
     struct X;
     struct Y;
     void f( int );
     void g( X );
 }
 namespace B
 {
     void f( int i )
     {
        f( i );   // which f()?
     }
 }




调用自身,用无限递归。原因是唯一可见的f()是B :: f()本身。

This f() calls itself, with infinite recursion. The reason is that the only visible f() is B::f() itself.

还有另一个函数带有签名f A.如果B写了using namespace A;或using A :: f;,则A :: f(int)在查找f ),并且f(i)调用在A :: f(int)和B :: f(int)之间是不明确的。因为B没有把A :: f(int)带入范围,但是,只能考虑B :: f(int),所以调用明确地解析为B :: f(int)。

There is another function with signature f(int), namely the one in namespace A. If B had written "using namespace A;" or "using A::f;", then A::f(int) would have been visible as a candidate when looking up f(int), and the f(i) call would have been ambiguous between A::f(int) and B::f(int). Since B did not bring A::f(int) into scope, however, only B::f(int) can be considered, so the call unambiguously resolves to B::f(int).

但是当我做了以下的...

But when I did the following..

 namespace A 
 {
     struct X;
     struct Y;
     void f( int );
     void g( X );
 }
 namespace B
 {
     using namespace A;
     void f( int i )
     {
        f( i );   // No error, why?
     }
 }

这意味着Herb Sutter已经错了?如果不是为什么我不会得到一个错误?

That means Herb Sutter has got it all wrong? If not why dont I get an error?

推荐答案

一个使用声明( A :: f )和using指令(使用命名空间A )。

There's a subtle difference between a using declaration (using A::f) and a using directive (using namespace A).

使用声明在其使用范围中引入一个名称,因此使用A :: f 调用 f B :: f(int)的定义中使用定义。

A using declaration introduces a name into the scope in which it is used so using A::f makes the call to f in the definition of B::f(int) ambiguous.

但在它们被使用的范围内可见,但是它们出现,如同该名称来自引入的命名空间的最近的公共范围以及使用using指令的命名空间。这意味着使用命名空间A; 在这种情况下使另一个 f 看起来好像是在全局范围但它仍然被 B :: f(int)隐藏。

A using definition makes members of the namespace visible in the scope in which it is used, but they appear as if the name comes from the nearest common scope of the namespace introduced and the namespace in which the using directive was used. This means that using namespace A; in this case make the other f appear as if it was declared at the global scope but it is still hidden by B::f(int).

(ISO / IEC / BS 14882: 2003 7.3.4 [namespace.udir] / 1为所有标准的垃圾。)

(ISO/IEC/BS 14882:2003 7.3.4 [namespace.udir] / 1 for all the standard junkies.)

这篇关于异常C ++ [Bug]?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆