【问题标题】:How do namespace's with same name but different scope (e.g. foo, bar::foo) work?名称相同但范围不同(例如 foo、bar::foo)的命名空间如何工作?
【发布时间】:2021-06-02 10:58:28
【问题描述】:

如果有两个命名空间FooBar,并且Bar 内部有一个命名空间Foo。如果我从Bar 内部引用变量Foo::i,它将在FooBar::Foo 中搜索i。如果没有,当iBar::Foo 中不存在时,是否可以让编译器在两个命名空间中搜索?

更具体地,在下面的示例中,我试图在 b 中的命名空间 a 中引用变量 i,而不添加额外的 ::。我知道输入:: 有效,我正在尝试看看是否有其他方法可以解决这个问题。

#include <iostream>
#include <string>

namespace a {
    int i = 1;
}

namespace b {
    namespace a {
    }
    
    namespace c {
        int j = a::i; // Doesn't work, need to use ::a::i;
    }
}
int main()
{
  std::cout << b::c::j << "\n";
}

【问题讨论】:

    标签: c++ namespaces


    【解决方案1】:

    如果您可以更改b::a,那么您确实可以将b::a 中的某些声明从::a 用作后备:

    namespace a {
        int i = 1;
        int j = 2;
    }
    
    namespace b {
        namespace a {
            namespace detail {
                using ::a::i; // Selectively bring declarations from ::a here
            }
            using namespace detail; // Make the names in detail available for lookup (but not as declarations).
            //int i = 2;
        }
        
        namespace c {
            int j = a::i; // Uses ::a::i
            // int k = a::j; // ERROR! We didn't bring ::a::j into b::a at all
        }
    }
    

    Here it is live.

    取消注释b::a::i 的声明将更改输出。由于正确的声明优先于命名空间 using 指令引入的名称。

    【讨论】:

      【解决方案2】:

      您可以在内部命名空间中显式地声明using,用于声明要从外部命名空间使用的变量。 即对于您的示例,

      namespace a {
          int i = 1;
      }
      
      namespace b {
          namespace a {
              using ::a::i; //inner one does not define its own
              int i2 = 2;   //inner one creates its own variable
          }
      
          namespace c {
              int j = a::i; // Doesn't work, need to use ::a::i;
          }
      }
      

      见: https://en.cppreference.com/w/cpp/language/namespace#Using-declarations

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-07-09
        • 1970-01-01
        • 2021-04-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多