About using directives in namespace in header files [duplicate]

  ambiguous, c++, cpp-core-guidelines, header-files, include

(This is kind of related to a previous question.)

Core guideline SF.7 gives a good motivation for avoiding to put using namespace directives at global scope in a header file.

However, even writing using namespace in a non-global namespace can be problematic. For example:

  • header1.hpp
    #include <boost/hana/transform.hpp>
    namespace ab {
        using namespace boost::hana;
        inline constexpr auto a = transform;
    }
    
  • header2.hpp
    #include <range/v3/view/transform.hpp>
    namespace ab {
        using namespace ranges::views;
        inline constexpr auto b = transform;
    }
    
  • main.cpp
    #include "header1.hpp"
    #include "header2.hpp"
    // here ab::b is ambiguous
    int main() {
    }
    

    with error (from clang)

    In included file: reference to 'transform' is ambiguous
    /home/enrico/header2.hpp:4:31:
    note: error occurred here
    /usr/include/boost/hana/fwd/transform.hpp:53:27:
    note: candidate found by name lookup is 'boost::hana::transform'
    :567:46:
    note: candidate found by name lookup is 'ranges::views::transform'
    

Is there a reason why the guidelines don’t mention this?

Should we entirely avoid using namespace n;/using n::x;/namespace n = m; at namespace scope?

Source: Windows Questions C++

LEAVE A COMMENT