请考虑这个例子,
我们如何在第二个参数是成员函数的指针的函数中强制进行隐式转换。
现在我要实现的功能不是在函数的参数列表中显式转换。
相反,我希望该编译器以某种方式像使用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;
}