Import nested classes into namespace

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.


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;

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.


你可以typedef

typedef A::B B;
链接地址: http://www.djcxy.com/p/78644.html

上一篇: C ++'typedef'与'using ... = ...'

下一篇: 将嵌套类导入名称空间