0

I have my classes/structs declared the following way:

namespace NS {
class A {
    public:
    struct B {
        int x;
        int y;
    }
}
}

int main() {
    NS::A::B objB;
}

I am wondering if there is any way I can refer to B in a more compact way. I tried using "using" but that only seems to work for namespaces.

shaveenk
  • 1,983
  • 7
  • 25
  • 37
  • if you have a C++11 compiler a type alias (`using`) should have worked though a `typedef` should suit your needs pre-C++11(and post-C++11 for that matter). How exactly did you try to use `using` and what error did you get? – YoungJohn Jul 30 '15 at 18:43
  • I think he thought of something like `using namespace NS::A;` (maybe with a somewhat different syntax) as if `A` was a nested namespace. At least, that's something i would have liked to do, but i can understand why it's not possible. But he can indeed use `using b_t = NS::A::B;` instead of `typedef NS::A::B b_t;` – Caninonos Jul 30 '15 at 18:46

4 Answers4

4

Use a typedef: typedef NS::A::B MyB.

Then your main becomes:

int main() {
    typedef NS::A::B MyB
    MyB objB;
}
Phil
  • 5,822
  • 2
  • 31
  • 60
2

I tried using "using" but that only seems to work for namespaces.

Using works just fine:

namespace NS {
    class A {
        public:
        struct B {
            int x;
            int y;
        };
    };
}

using MyB = NS::A::B;

int main() {
    NS::A::B objB;
    MyB objB2;
}

There is some discussion on SO about this solution as opposed to the typedef approach. The conclusion is that they are equivalent.

Community
  • 1
  • 1
Moby Disk
  • 3,761
  • 1
  • 19
  • 38
  • there is the possibility the compiler used by the OP is pre-C++11 and does not support type aliases – YoungJohn Jul 30 '15 at 18:46
  • (you can also move either `using` or `typedef` inside the `main`'s body, just to emphasize that this solution isn't any different from Phil's which uses `typedef`) – Caninonos Jul 30 '15 at 18:49
  • @YoungJohn Then it's not a C++ compiler. – o11c Jul 30 '15 at 18:52
1

typedef ? Tested in Code Blocks:

namespace NS {
class A {
    public:
    struct B {
        int x;
        int y;
    };
};
}
typedef NS::A::B NSAB;


int main() {

    //NS::A::B objB;
    NSAB objc;

}
tryanswer
  • 11
  • 1
1

You want an alias-declaration, not a using-declaration or using-directive. You need to provide a name:

using AB = NS::A::B;

This is particularly more readable in some cases, and can be used in templates unlike typedef.

For example:

template<class T>
struct Foo {
    struct Bar {};
};

template<class T>
using Bar = typename Foo<T>::Bar;
o11c
  • 15,265
  • 4
  • 50
  • 75