c++在对象上调用特定类的虚函数

Call Virtual Function for Specific Class on Object in C++

本文关键字:函数 对象 调用 c++      更新时间:2023-10-16

我需要从类外部的某个对象上从"声明"类型调用函数。我做了一个小的代码样本,并把所需的行为作为注释,因为我不知道究竟如何问这个:)

template<typename T>
void hun(T* obj, class C* c)
{
    //do some checking on c
    if(some conditions from c are true)
    {
        //call fun from T ignoring it's virtual
    }
}
struct A
{
    virtual void fun(){};
    virtual void gun(class C* c)
    {
        //do something specific to A
        hun(this, c); //here call fun from A even if real type of this is B
    };
}
struct B : public A
{
    void fun(){};
    void gun(class C* c)
    {
        //do something specific to B
        hun(this, c);//here call fun from B even if real type of this is something derived from B
    };
}

有可能实现这种行为吗?

我知道我可以使用A::fun()B::fun()从类内部调用fun(),但是hun()的检查对所有类都是常见的,我不想用这个代码污染gun()

(这可能已经在其他地方回答过了…)

可以使用限定id显式调用虚函数的一次重写。成员函数的限定id的形式为my_class::my_function

参考,参见c++ Standard [expr.call]/1:

如果选择的函数是非虚函数,或者类中的id-表达式成员访问表达式是限定id,则调用该函数。否则,它的最终重写(10.3)在调用对象表达式的动态类型。

例子
template<typename T>
void hun(T* obj, class C* c)
{
    //do some checking on c
    if(some conditions from c are true)
    {
        //call fun from T ignoring it's virtual
        obj->T::fun(); // T::fun is a qualified-id
    }
}
struct A
{
    virtual void fun(){};
    virtual void gun(class C* c)
    {
        //do something specific to A
        hun(this, c); //here call fun from A even if real type of this is B
    };
}; // note: semicolon was missing
struct B : public A
{
    void fun(){};
    void gun(class C* c)
    {
        //do something specific to B
        hun(this, c);//here call fun from B even if real type of this is something derived from B
    };
};