I have some code which looks like this:
namespace myLibrary
{
class A
{
public:
struct Nested
{
...
};
...
};
}
In some other parts of the code, I need to access A. Since I like readable code, I also like the using directive:
using myLibrary::A;
...
A a;
Now, at some point I also need to access my nested class, so I want to write something like this:
using myLibrary::A::Nested;
Obviously, the compiler can't know that this is a nested class and not a class member, and gives me an error:
error : using declaration can not refer to class member
What I can't understand is why this does not solve the problem:
using typename myLibrary::A::Nested;
The compiler still gives me the exact same error!
Luckily, I have alternatives:
// Using a typedef
typedef myLibrary::A::Nested Nested;
// Using the new C++11 syntax for type aliasing
using Nested = myLibrary::A::Nested;
but I'd like to understand why the using typename directive did not work. Does it not do what I think it does? Or is it not implemented by compilers? If it is the latter, is there a reason for it?
Nested
must always be referred to asA::Nested
unless it's in member variables or functions ofA
. If your code seems to call for talking aboutNested
withoutA::
, that's a sign that it might be a better design not to have it as a nested class. – Consoletypedef
? That's almost the same as a using-declaration, just more boilerplate. IMO, it leads to the question why isn't it allowed to use a using-declaration naming a nested type outside a derived class? – Monteith