【问题标题】:C++ namespace: using without owningC++ 命名空间:使用而不拥有
【发布时间】:2016-12-16 14:39:54
【问题描述】:

我想在我的命名空间中使用来自另一个命名空间的东西,而不是让它成为我命名空间的一部分。更具体的我有以下情况:

namespace my_ns{
    enum class c: unsigned long long int{};

    namespace literals{
        constexpr c operator"" _c(unsigned long long int i)noexcept{
            return c(i);
        }
    }

    using namespace literals;

    auto xyz = 4_c; // OK: use literals::operator""_c
}

void some_function(){
    using namespace my_ns; // shall not implicit include my_ns::literals!

    auto abc = xyz; // OK
    auto def = 4_c; // shall not know my_ns::literals::operator""_c
}

我想在my_ns 中使用用户文字,但为了与stdstd::literals 保持一致,而不是some_functionusing namespace 之后。您认为一致性争论值得头疼吗?

如果是,有没有办法做到这一点或做类似的事情?

【问题讨论】:

  • 答案很简单:不要用 using 指令破坏你的命名空间。
  • 问题来了:如果您不打算让任何人使用它,为什么还要创建自定义文字?

标签: c++ namespaces using


【解决方案1】:

您可以尝试使用嵌套的 detail 命名空间,然后只向主 my_ns 命名空间公开您想要的内容:

namespace my_ns
{
    namespace detail
    {
        using namespace literals;
        auto xyz = 4_c; // OK: use literals::operator""_c
    }

    using detail::xyz;
}

【讨论】:

    【解决方案2】:

    您可以使用另一个命名空间,然后将其公开

    namespace Rtos
    {
      constexpr unsigned long long operator "" ms(unsigned long long ms) 
      {
        return ms / portTICK_PERIOD_MS ; 
      } ;
    }
    
    namespace GlobalVars
    {
      using Rtos::operator""ms ;
      Rtos::Event event{1000ms, 1} ;
    }
    
    using GlobalVars::event ;
    
    void SomeFunction()
    {
      event.Signal();
    }
    

    【讨论】:

      猜你喜欢
      • 2014-07-17
      • 1970-01-01
      • 1970-01-01
      • 2010-12-23
      • 1970-01-01
      • 1970-01-01
      • 2011-07-15
      • 1970-01-01
      • 2013-09-27
      相关资源
      最近更新 更多