请考虑这个例子, 我们如何强制隐式转换函数的第二个参数是指向成员函数的指针。 明确地在函数的参数列表中进行投射并不是我现在想要的功能。 相反,我会喜欢的编译器在某种程度上是这样做它与第一个参数呢?如何强制多态中的隐式转换?
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;
}
我怀疑这是不能做到的。在func中,你知道(静态)你正在处理一个Base对象,并假装任何Base对象都有该方法是不安全的。 - 另外,仅仅因为有指针参与,并不意味着你必须使用'new/delete':'派生测试; func(&test,&Derived :: f);' – visitor 2012-01-06 11:22:38
这个问题还不够清楚。请解释一下。 – 2012-01-06 11:56:14
我希望能够通过一个指向成员方法的指针,该指针用于指向成员参数的函数参数。在我的例子中,函数应该采用“polimorph”类型,但不会。 – codekiddy 2012-01-06 13:09:59