請考慮這個例子, 我們如何強制隱式轉換函數的第二個參數是指向成員函數的指針。 明確地在函數的參數列表中進行投射並不是我現在想要的功能。 相反,我會喜歡的編譯器在某種程度上是這樣做它與第一個參數呢?如何強制多態中的隱式轉換?
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