如何在多态性中强制隐式转换? [英] How to force implicit conversion in polymorphism?

查看:99
本文介绍了如何在多态性中强制隐式转换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑这个例子,
我们如何在函数中强制隐式转换,其第二个参数是指向成员函数的指针。
在函数的argument参数列表中显式转换不是我想要的achive wright。
相反,我希望编译器这样做像FIRST参数...

Please consider this example, how do we force implicit conversion in function whose second parameter is pointer to member function. casting explicitly in argument list of function is not what I want to achive wright now. Instead I would like that compiler somehow do that like it does with FIRST parameter...

struct Base
{
    virtual ~Base() = 0 {}
};

struct Derived : public Base
{
    void f(){}
};

typedef void(Base::*polymorph)();

// how do I force IMPLICIT conversion here: EDIT: (polymorph type work only for polymorph pointer type no conversion)
void func(Base* arg1, polymorph arg2) // void* arg2, (void*) arg2 etc...  dosn't work
{
    polymorph temp = reinterpret_cast<polymorph>(arg2); // to achive this
}

int main()
{
    Derived* test = new Derived;
    // first parameter work but another gives an error
    func(test, &Derived::f); // BY NOT CHANGING THIS!
    delete test;
    return 0;
}


推荐答案

代码如下。但是我不知道当temp实际被调用时,this指针将被引用。

As clean as it gets. Code below. But I have no idea who's "this" pointer is going to be referenced when "temp" actually gets invoked.

typedef void(Base::*polymorph)(); 

void func(Base* arg1, polymorph arg2)
{ 
    polymorph temp = arg2;
} 


int main() 
{ 
    Derived* test = new Derived; 
    // first parameter work but another gives an error 
    func(test, static_cast<polymorph>(&Derived::f)); 
    delete test; 
    return 0; 
} 

这篇关于如何在多态性中强制隐式转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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