2013-06-03 60 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:很高兴帮助 –