【问题标题】:Can I use some but not all names from a namespace without having to repeat the full scope for all of them?我可以使用命名空间中的一些但不是全部名称,而不必为所有名称重复全部范围吗?
【发布时间】:2021-01-01 06:53:17
【问题描述】:

在我的代码中我写了好几次类似

// all these using
using this::is::a::very::long::name::space::var1;
using this::is::a::very::long::name::space::var2;
using this::is::a::very::long::name::space::var3;
using this::is::a::very::long::name::space::fun1;
using this::is::a::very::long::name::space::fun2;
// to make this line cleaner
fun1(var1,fun2(var2,var3));

因为我不想让该命名空间中的任何名称可用,除了我列出的 5 个名称。

C++ 是否提供任何东西来使用所有这些名称,而不必一遍又一遍地编写范围的公共部分?

【问题讨论】:

  • 这能回答你的问题吗? In C++, what is a "namespace alias"?
  • 我不太确定这是不是重复的。这不是关于缩短命名空间,而是询问一种减少using 声明数量的工具,就像python 拥有from package import x, y, z 一样。 C++ 没有这样的工具,但这并没有真正使问题成为“什么是命名空间别名”的重复
  • 我看到了一些使用复杂宏功能的宏功能,它可以让你做USING(this::is::a::very::long::name::space, var1, var2, var3, fun1, fun2) ...但我认为“治疗”比它试图解决的问题更糟糕(因为我讨厌宏)。

标签: c++ namespaces


【解决方案1】:

您问题的一个关键点似乎是您需要经常这样做。为了缓解这种情况,您可以在指定的命名空间中填充这些符号。

namespace common_stuff {
  // You can also use an alias as the other answer suggests to shorten this
  using this::is::a::very::long::name::space::var1;
  using this::is::a::very::long::name::space::var2;
  using this::is::a::very::long::name::space::var3;
  using this::is::a::very::long::name::space::fun1;
  using this::is::a::very::long::name::space::fun2;
}

using 声明是一个声明,因此我们创建了一个命名空间,其中仅五个声明用于您想要的东西。现在,在您希望这五个对于非限定名称查找可见的每个范围内,您只需添加

using namespace common_stuff;

只有来自common_stuff 的那五个符号会被显示出来。

【讨论】:

    【解决方案2】:

    你可以使用namespace alias:

    // Create an alias namespace of the long namespace
    namespace shorter = this::is::a::very::long::name::space;
    
    using shorter::var1;
    using shorter::var2;
    using shorter::var3;
    using shorter::fun1;
    using shorter::fun2;
    

    如果您使别名足够短,您甚至可能根本不需要 using 声明。但除此之外,没有任何其他方便的方法可以从命名空间中拉入少量符号而不拉入所有内容。

    C++ 没有任何方法可以使符号 x,y,z 在某些命名空间 ns 中可见,而无需重复的 using 声明。

    【讨论】:

    • 嗯,这似乎是一个很高兴拥有功能。你知道他们是否在以某种方式考虑吗?
    • 我同意这将是一个很好的功能。我快速浏览了一些最近/开放的提案here,但我没有看到任何明确的内容(尽管我可能错过了它)。如果它至少没有被提出一次,我会感到惊讶。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-12-22
    • 1970-01-01
    • 2020-11-01
    • 2016-12-15
    • 1970-01-01
    • 1970-01-01
    • 2012-03-28
    相关资源
    最近更新 更多