2013-06-03 58 views
4

這是我的課使用函數指針

template <typename TValue, typename TPred = std::less<TValue> > 
class BinarySearchTree { 
public: 
BinarySearchTree<TValue, TPred> &operator=(BinarySearchTree<TValue, TPred> const &tree) { 
    if (this != &tree) { 
     tree.VisitInOrder(Insert); 
    } 
    return *this; 
} 
bool Insert(TValue const &value) { 
    return m_Insert(value, pRoot); 
} 
template <typename TVisitor> void VisitInOrder(TVisitor visitor) const; 
... 
}; 

的選擇,並按照以下順序不會工作:VisitInOrder(Insert),因爲我的編譯器說有爭論缺少

,但我的主要看起來像這樣在那裏我可以使用函數沒有它的參數:

void Print(int const x) { cout << x << endl; } 

int main() { 
    BinarySearchTree<int> obj1, obj2, obj3; 
    obj1.Insert(10); 
    obj1.VisitInOrder(Print); 
    return 0; 
} 

完整的代碼在這裏:http://pastebin.com/TJmAgwdu

回答

3

您的功能Insert是一個成員函數,這意味着它接受隱式的this指針。你必須使用std::bind(),如果你想獲得一個一元仿函數出Insert()

if (this != &tree) { 
    tree.VisitInOrder(
     std::bind(&BinarySearchTree::Insert, this, std::placeholders::_1)); 
} 

下面是該程序時,下面的賦值存在編譯live example

obj3 = obj1; 
+0

@Praetorian:哎呀: )編輯,謝謝! –

+0

感謝,偉大的作品 – schreda

+0

@schreda:很高興幫助 –