将嵌套类导入命名空间

将嵌套类导入命名空间

本文介绍了将嵌套类导入命名空间 - C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有这样的类:

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

我可以参考 B c $ c> A :: B 和 f() as A :: f $ c>,但是我可以导入 B f()到全局/当前命名空间?我尝试了

 使用A :: B; 

但是给我一个编译错误。

解决方案

您应该可以为类使用命名空间别名:

  = A :: B; 

但是你不能使用成员函数,甚至不能使用静态成员函数。 p>

修改:根据这个应该是有效的,实际上创建一个类型别名的方式与 typedef






在C ++ 11中有一个静态成员函数的解决方法,声明一个指向静态函数的变量:

  struct Foo 
{
static void bar b $ b {}
};

auto bar = Foo :: bar;

编辑:当然,有一个全局变量指向一个静态成员函数在旧的C ++标准中也是可能的,但它比使用C ++ 11的 auto 关键字更麻烦。在上面的例子中,它将是:

  void(* bar)()= Foo :: bar; 


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;

这篇关于将嵌套类导入命名空间 - C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 21:21