C ++:指向虚拟成员函数的单形式版本? [英] C++: Pointer to monomorphic version of virtual member function?

查看:157
本文介绍了C ++:指向虚拟成员函数的单形式版本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++中,可以获取指向类的(非静态)成员函数的指针,然后稍后在对象上调用它。如果函数是virtual,则根据对象的动态类型动态调用调用。也可以(不使用成员指针)通过显式地提供包含要使用的版本的范围来单形地调用对象的虚拟成员函数。下面的代码演示了这一点:

In C++, it's possible to get a pointer to a (non-static) member function of a class, and then later invoke it on an object. If the function was virtual, the call is dispatched dynamically depending on the dynamic type of the object. It's also possible (not using a member pointer) to call virtual member functions of objects monomorphically, by explicitly providing the scope containing the version to use. The following code demonstrates this:

#include <iostream>
using std::cout; using std::endl;

struct Foo
{
    virtual void foo() { cout << 1 << endl; }
};

struct Foo2: public Foo
{
    virtual void foo() { cout << 2 << endl; }
};

int main( int, char** )
{
    Foo *foo = new Foo2;

    void (Foo::*foo_pointer)() = &Foo::foo;

    foo->foo();            // prints 2
    foo->Foo::foo();       // prints 1
    (foo->*foo_pointer)(); // prints 2
}

我想做的是合并两者,获取指向成员函数的单形式版本的指针;即,我想要一个指向Foo :: foo的指针,它总是调用foo的基类版本,并打印1,即使它在Foo2上被调用。但是,我还没有找到办法做到这一点。是否有可能?

What I would like to do is combine the two, and get a pointer to the monomorphic version of a member function; i.e., I want a pointer to Foo::foo which always calls the base class version of foo, and prints 1, even if it is invoked on a Foo2. However, I haven't been able to find a way to do this. Is it possible?

(除了编​​写一个新的非虚函数,这使得单形调用,然后得到一个指针的繁琐的手动方式) / p>

(Other than the tedious manual way of writing a new non-virtual function which makes the monomorphic call, and then getting a pointer to that.)

推荐答案

这可能在 GCC ,但是它在C ++语言扩展部分中的记录方式表明没有可移植的方法。

It's possible in GCC, but the way it's documented in C++ language extensions section suggests there's no portable way to do it.

你可以做两件事:


  1. 如果你控制类,创建一个非虚函数和一个虚拟包装器,当你知道你不需要

  2. 如果没有,请创建一个模板函数,它将保存成员指针并进行显式范围调用。

这篇关于C ++:指向虚拟成员函数的单形式版本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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