指的是堂兄名称空间

问题描述 投票:0回答:2

我有一个类似于this question的问题,但有一个额外的深度:

namespace root { namespace parent1 { namespace childa {
    class hard_to_get_at{};
}}}

namespace root { namespace parent2 { namespace childb {
    // how do I refer refer to namespace childb relative to the current namespace ?
    void someFunc()
    {
       parent1::childa::hard_to_get_at instance; // does not work
    }
}}}

当我尝试上述操作时,我收到了错误消息

错误:'root :: parent :: child :: parent 1 :: child'尚未声明

我不明白为什么这不起作用,我得到它应该的印象。我真的不想在someFunc函数中放置一个using声明。

这发生在g ++ 4.5中,启用了c ++ 0x选项

c++ namespaces
2个回答
2
投票

你错过了一些开头括号:

namespace root { namespace parent1 { namespace childa { // <--- here
    class hard_to_get_at{};
}}}

namespace root { namespace parent2 { namespace childb { // <--- and here
    // how do I refer refer to namespace childb relative to the current namespace ?
    void someFunc()
    {
       parent1::childa::hard_to_get_at instance; // does not work
    }
}}}

这是缩进很重要的原因之一。


1
投票

老问题,但我有同样的问题(或相同的症状),至少在我的情况下,这个问题非常棘手,所以发布以防万一。

基本上,如果parent1childb中的命名空间,从TU可以看到,查找将失败。例如:

namespace a { namespace b { namespace c {
class hard_to_get_at {};
}}}

namespace a { namespace d { namespace e {
namespace b {}  // May be in any included '.h'
void f() {
  b::c::hard_to_get_at foo;  // Previous line introduced a::d::e::b which is found before a::b, compiler doesn't backtrack when a::d::e::b::c isn't found.
}
}}}

虽然我无法确定所有代码,但我的猜测实际上是OP的问题,因为错误消息“error: 'root::parent2::childb::parent1::childa' has not been declared”表明编译器发现了命名空间root::parent2::childb::parent1,如果它在那里寻找childa

顺便说一句,这可以用更少的嵌套来复制,这使得问题更加明显:

namespace a {
class Foo {};
}

namespace b {
namespace a {}
void f() { a::Foo foo; }  // This will fail because 'a' here is '::b::a'
}
© www.soinside.com 2019 - 2024. All rights reserved.