没有函数指针参数的隐式向上转换?

时间:2017-07-29 16:34:26

标签: c++ function pointers contravariance upcasting

这是我遇到的一种奇怪的情况。我期望指针隐式向上翻译:

struct BaseClass
{};

struct DerivedClass : BaseClass
{};

void baseClassArgFunc(BaseClass* arg) {}            // Function taking BaseClass argument
void derivedClassArgFunc(DerivedClass* arg) {}      // Function taking DerivedClass argument

int main()
{
    void (*pBaseFuncArg) (BaseClass*);      // Pointer to function taking BaseClass argument
    void (*pDerivedFuncArg) (DerivedClass*);    // Pointer to function taking DerivedClass argument

    pBaseFuncArg = baseClassArgFunc;            // Assign pointer, works fine
    pDerivedFuncArg = derivedClassArgFunc;      // Assign pointer, works fine

    pBaseFuncArg = derivedClassArgFunc;         // A value of type void (*) (DerivedClass *arg) cannot be 
                                                // assigned to an entity of type void (*) (BaseClass *)

    pDerivedFuncArg = baseClassArgFunc;         // A value of type void (*) (BaseClass *arg) cannot be 
                                                // assigned to an entity of type void (*) (DerivedClass *)

    return 0;
}

我期望将void(*)(DerivedClass *)赋值为void baseClassArgFunc(BaseClass * arg)是安全的。我很困惑。我想那时函数指针参数没有隐式向上转换?

1 个答案:

答案 0 :(得分:3)

更改课程以揭露问题:

struct BaseClass
{
};

struct DerivedClass : BaseClass
{
    int a;
};

然后

pBaseFuncArg = derivedClassArgFunc;

对于:

不安全
 void derivedClassArgFunc(DerivedClass* arg) { arg->a = 42; }


 int main()
 {
     void (*pBaseFuncArg) (BaseClass*) = derivedClassArgFunc;
     BaseClass base;

     //derivedClassArgFunc(&base); // Doesn't compile as expected
     pBaseFuncArg(&base);          // Would be UB, base->i won't exist
 }