为什么不能使用范围解析与成员指针解引用? [英] Why can't one use scope resolution with member pointer dereference?

查看:171
本文介绍了为什么不能使用范围解析与成员指针解引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑一个简单的例子:

struct FooParent {
   virtual void bar() { }
};

struct Foo: FooParent {
   void bar() { }
};

int main() {
   Foo foo;
   void (Foo::*foo_member)() = &FooParent::bar;
   //(foo.*FooParent::foo_member)();
   foo.FooParent::bar();
}

正如你可以看到一个可以使用范围解析的 foo 对象当调用bar成员函数时,没有办法显式声明成员函数指针的作用域。我接受当使用 - > * 时,应该禁止语法,因为操作符可能以有时意外的方式重载,但是我不能理解防止显式范围解析的原因解除引用

As you can see one can use scope resolution on the foo object when calling bar member function while there is no way to explicitly declare the scope for member function pointer. I accept that the syntax should be prohibited when using ->* as the operator can be overloaded in sometimes unexpected way, but I cannot understand the reason behind preventing explicit scope resolution when dereferencing with .*.

我试图禁用一个指向基类的成员指针的虚拟分派虚拟函数。

I am trying to disable virtual dispatch for a member pointer that points to a base class's virtual function.

推荐答案

你声明的变量的名称是 foo_member ,在本地块范围内。不是 Foo :: foo_member 的名称,即 Foo 没有成员 foo_member 。相比之下, bar 的名称位于类 Foo 的范围内,并且在类 FooParent

The name of the variable you declared is foo_member, inside your local block scope. It is not a name Foo::foo_member, i.e. the class Foo has no member foo_member. By contrast, the name bar lives in the scope of the class Foo, and also in the scope of the class FooParent.

所以范围解析机制按预期工作:它解析范围。

So the scope resolution mechanism works as expected: it resolves the scope.

[更新:]没有通过成员函数指针禁用虚拟分派的机制。你可以这样调用基本子对象的成员函数:

[Update:] There is no mechanism to disable virtual dispatch through a member function pointer. You can call a member function of the base subobject like this:

 void (FooParent::*p)() = &FooParent::bar;
 (static_cast<FooParent&>(foo).*p)();

但是呼叫仍然最终被虚拟调度。成员函数的虚拟性被嵌入成员函数指针值。你可以做的下一件最好的事情是使用lambda:

But the call still ends up getting dispatched virtually. The virtuality of the member function is baked into the member function pointer value. The next best thing you can do is to use a lambda:

auto q = [](FooParent & f) { f.FooParent::bar(); };
q(foo);

这篇关于为什么不能使用范围解析与成员指针解引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆