0

(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?


Related

In this question of mine I have self-answerd with a way to use those directives when defining an object in a header file, but without cluttering anything, by wrapping all RHS of assignment in a void-to-desired-object lambda called in place.

Enlico
  • 23,259
  • 6
  • 48
  • 102
  • 1
    Yes avoid using namespace in header files period. They become painful very quickly. https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice. I think what you describe is just another version of the same guideline. – Pepijn Kramer Sep 14 '21 at 19:07
  • 2
    Why would `ab::b` be ambiguous? – Remy Lebeau Sep 14 '21 at 19:08
  • @RemyLebeau, because both `boost::hana::transform` and `ranges::views::transform` can take 2 arguments. – Enlico Sep 14 '21 at 19:09
  • 1
    Since namespace aliases are a thing, IMHO there is no reason to use `using namespace ...;`. Sure there is some more type involved, but avoiding name conflicts is worth it. – NathanOliver Sep 14 '21 at 19:10
  • @RemyLebeau, I've added the error. – Enlico Sep 14 '21 at 19:13
  • 1
    Possibly related: [scope of using declaration within a namespace](https://stackoverflow.com/questions/6175705/) – Remy Lebeau Sep 14 '21 at 19:13
  • @RemyLebeau, thanks, that answers my question! – Enlico Sep 14 '21 at 19:19

0 Answers0