我想這一點,和它的一些變化:如何重載 - > *運算符?
template<class T>
class Ptr {
public:
Ptr(T* ptr) : p(ptr) {}
~Ptr() { if(p) delete p; }
template<class Method>
Method operator ->* (Method method)
{
return p->*method;
}
private:
T *p;
};
class Foo {
public:
void foo(int) {}
int bar() { return 3; }
};
int main() {
Ptr<Foo> p(new Foo());
void (Foo::*method)(int) = &Foo::foo;
int (Foo::*method2)() = &Foo::bar;
(p->*method)(5);
(p->*method2)();
return 0;
}
但doesn't work。問題是我真的不知道作爲一個參數期望什麼或返回什麼。這個標準對我來說是不可理解的,而且由於Google沒有提供任何有用的信息,我想我並不孤單。
編輯:闖闖,用C++ 0x中:http://ideone.com/lMlyB
聽起來很可怕。我得看一看。 – Fozi 2011-04-07 20:50:49
@Fozi:相信我,就是這樣。儘管我找不到完整的實現,但您的智能指針只需要從某個基地繼承而來,並且所有'operator - > *'功能都將存在。 :| – Xeo 2011-04-07 20:53:14
我實際上有一個Delegate類可能可以做到這一點,但它相當重量級,所以我想避免將它作爲臨時返回。 '(* p)。* method'要簡單得多,儘管我希望我可以輕鬆地支持' - > *'。 – Fozi 2011-04-07 21:00:25