请考虑这个例子, 我们如何在函数中强制隐式转换,其第二个参数是指向成员函数的指针。 在函数的参数列表中明确地进行转换并不是我现在想要的。 相反,我希望那个编译器以某种方式像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;
}
答案 0 :(得分:2)
尽可能干净。代码如下。但是当我真正调用“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;
}