gpt4 book ai didi

c++ - 如何在多态性中强制隐式转换?

转载 作者:行者123 更新时间:2023-11-30 04:30:21 25 4
gpt4 key购买 nike

请考虑这个例子,我们如何在第二个参数是指向成员函数的指针的函数中强制进行隐式转换。在函数的参数列表中显式转换不是我现在想要实现的。相反,我希望编译器以某种方式像使用 FIRST 参数那样做......

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”指针。

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;
}

关于c++ - 如何在多态性中强制隐式转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8756993/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com