25

Say I have a class like this:

class A {
public:
    class B {
        // ...
    };
    static void f();
    // ...
};

I can refer to B as A::B and to f() as A::f(), but can I import B and f() into the global/current namespace? I tried

using A::B;

but that gave me a compilation error.

Eitan T
  • 32,660
  • 14
  • 72
  • 109
Baruch
  • 20,590
  • 28
  • 126
  • 201

3 Answers3

33

Here are two workarounds for your problem:

1) Class B:

typedef A::B B;

2) Function f():

inline void f()
{
    A::f();
}

But think twice before using them.

Edit: In C++11 you can do auto f = A::f; but this actually creates a pointer to a function and functions pointers cannot be inlined.

Sergey K.
  • 24,894
  • 13
  • 106
  • 174
  • For the `typedef`or `using` solutions, any idea to make it work even with private nested class? – Dreamer Feb 11 '17 at 01:05
19

You should be able to use namespace aliases for the class:

using B = A::B;

However you can't do that with the member function, not even with static member functions.

Edit: According to this SO answer (What is the difference between 'typedef' and 'using' in C++11) this should be valid, and actually creates a type alias in the same way that typedef does. However, it's C++11 only.


There is a workaround for static member functions in C++11, by declaring a variable pointing to the static function:

struct Foo
{
    static void bar()
        { }
};

auto bar = Foo::bar;

Edit: Of course, having a global variable pointing to a static member function is possible in the older C++ standard as well, but it's more messy than using the auto keyword of C++11. In the example above it would be:

void (*bar)() = Foo::bar;
Community
  • 1
  • 1
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
11

You can typedef

typedef A::B B;
Andrew
  • 24,218
  • 13
  • 61
  • 90