user13865989
user13865989

Reputation:

'using namespace {some namespace nested inside of another}`

Is it possible to access the type Foo under the namespace first by using a using declaration (or something similar) in the caller code?

namespace first {
    namespace second {
        struct Foo { int i; }; 
    } 
} 

int main() {
    using namespace first::second; 
    first::Foo foo { 123 }; 
    return 0; 
}

I get these error messages:

error: 'Foo' is not a member of 'first'
  first::Foo foo{ 123 };```

Upvotes: 4

Views: 93

Answers (2)

Thomas Sablik
Thomas Sablik

Reputation: 16454

Namespaces can be expanded and you can create an alias to a token in a different namespace:

namespace first {
    namespace second {
        struct Foo { int i; }; 
    } 
}

namespace first {
    using second::Foo;
}

int main() {
    first::Foo foo { 123 }; 
    return 0; 
}

Upvotes: 0

HolyBlackCat
HolyBlackCat

Reputation: 96033

You have several options:

  1. using namespace first::second; 
    Foo foo{123};
    
  2. namespace ns = first::second; 
    ns::Foo foo{123};
    
  3. I guess you could also do namespace first = first::second;. Then first::Foo foo{123}; would work, but to access the contents of the actual namespace first (other than those in namespace second) you'll have to use ::first.

Upvotes: 5

Related Questions