jterm jterm - 2 months ago 8
C++ Question

How do I access an alias declared inside struct/class scope?

With the following code

Header.h

namespace some_name {
struct foo {
// using alias
using MyMap = std::map<double, some_class* const>;
MyMap* GetMap();
MyMap* map_;
}
}


Source.cpp

#include "Header.h"

// using declaration
using some_name::foo;

MyMap* foo::GetMap(){
...
return map_;
}


When I compile I get a compiler error that states:


error: ‘MyMap’ does not name a type

MyMap* foo::GetMap() {

^


However if I define
GetMap()
in place in the header file everything works fine but if I move it to source file I get that error. What am I missing here?

Answer

The line

using some_name::foo;

In your code just imports the name foo into the current scope. That means that any time the compiler see's the unqualified name foo it will know you are using some_name::foo.

This will not help you with MyMap though. MyMap is scoped by foo so in order to access you still need to use foo:: like

foo::MyMap* foo::GetMap()

Another option would be to add another using statement to bring in MyMap but this will pollute the scope with that name so you may not want to do that. If you do then you can use

// using declaration
using some_name::foo;
using MyMap = some_name::foo::MyMap;

MyMap* foo::GetMap(){
    ...
    return map_;
}