将嵌套类导入命名空间 - C++
假设我有这样的课程:
class A {
public:
class B {
// ...
};
static void f();
// ...
};
我可以将 B
称为 A::B
并将 f()
称为 A::f()
,但我可以将 B
和 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.
根据this SO answer(What is the difference between 'typedef' and 'using'在 C++11) 这个 应该 是有效的,并且实际上以与 typedef
相同的方式创建类型别名.但是,它只是 C++11.
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.
在 C++11 中有一个静态成员函数的解决方法,通过声明一个指向静态函数的变量:
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;
当然,在旧的 C++ 标准中也可以有一个指向静态成员函数的全局变量,但它比使用 auto
更混乱C++11 的关键字.在上面的示例中,它将是:
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;
相关文章