spraff
spraff

Reputation: 33405

Can I "import" one namespace into another in the header?

Foo.h

namespace Foo
{
    namespace Inner
    {
        void func (int *);
    }
}

Bar.h

#include <Foo.h>

namespace Bar
{
    namespace Inner
    {
        void func (float *);
    }
}

main.cpp

#include <Bar.h>

using namespace Bar;

int main ()
{
    int i;
    float f;

    Inner::func (&i);
    Inner::func (&f);
}

In main the float * overload of func is available without a Bar:: namespace qualifier, but the int * overload requires a Foo:: namespace qualifier.

I know I could have

using namespace Foo::Inner;
using namespace Bar::Inner;

int main ()
{
    int i;
    float f;

    func (&i);
    func (&f);
}

I do not want this, I want to refer to Inner::func as such in each case.

I also do not want to add using namespace Foo to every .cpp file which includes Bar.h (this is the result of a library refactoring effort, pulling some of Bar out into Foo, many .cpp files already include Bar.h).

I view this informally as "importing" Foo::Inner into Bar::Inner, hence the question title. What I really mean is:

Can I add something to Bar.h which will let me refer to the overloads in Foo::Inner as Inner::stuff wherever using namespace Bar is in effect?

Upvotes: 5

Views: 1013

Answers (3)

francesco
francesco

Reputation: 7539

Use

namespace Inner {
  using namespace Foo::Inner;
  using namespace Bar::Inner;
}

before main. See live example here

Upvotes: 5

Bathsheba
Bathsheba

Reputation: 234715

Writing

namespace Inner
{
    using namespace Foo::Inner;
    using namespace Bar::Inner;
}

just above main does this. If you want to bring in only specific symbols, then write using Foo::Inner::func &c.

Upvotes: 2

user7860670
user7860670

Reputation: 37587

You can place using into Bar::Inner:

namespace Bar
{
    namespace Inner
    {
        using Foo::Inner::func;
        void func (float *);
    }
}

This way both overloads can be referred with Bar::Inner::func.

Upvotes: 6

Related Questions