Search code examples
c++namespacesusing

C++ namespace: using without owning


I want to use stuff from another namespace in my namespace, without making it part of my namespace. More concrete I have the following situation:

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
}

I want to use the user literals in my_ns but for consistency with std and std::literals not in some_function after the using namespace. Do you think the consistency argument is worth the headaches?

And if it is, is there a way to do it or to do something similar?


Solution

  • You could try using a nested detail namespace and then expose only what you want to the main my_ns namespace:

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