4

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 };```
7
  • 1
    What is "something like this"? Commented Jul 5, 2020 at 19:07
  • Have you tried yourself before asking? Having any issues with your code? By the way, why you declare as first::Foo while the struct Foo is inside second? Commented Jul 5, 2020 at 19:11
  • @ThomasSablik access the type Foo under namespace first. Commented Jul 5, 2020 at 19:17
  • @armagedescu yes I have tried, and that was part of the question. Sorry I didn't make it clear enough. Commented Jul 5, 2020 at 19:18
  • Then you should edit the question with the compiler error messages that you got. Commented Jul 5, 2020 at 19:18

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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; 
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.