2015-06-06 88 views
0

考虑下面的代码:访问二叉搜索树的功能

#include "ClassB.h" 

ClassA 
{ 
private: 
    Vector<std::string> idVec; 

public: 
    int getTotal(ClassB& (*func) (std::string)); 
} 

int ClassA::getTotal(ClassB& (*func) (std::string)) 
{ 
    int total = 0; 
    for (int i:0; i < idVec.Size(); i++) 
    { 
     total += (*func) (idVec[i]).GetInt(); 
    } 
return total; 
} 

ClassB 
{ 
private: 
    string id; 
    int i; 

public: 
    std::string getId(); 
    int getInt(); 
} 

ClassB& accessTree(stD::string id); 

main() 
{ 
    BSTree<ClassB> //Binary Search Tree 
    ClassA a; 
    //Assume id's get set. 
    a.getTotal(accessTree); 
} 

ClassB& accessTree(stD::string id) 
{ 
    //This is part I'm not 100% on. 
} 

ClassB的的运营商已经超载。如果你愿意的话,请考虑它是主键。

**编辑 感谢Joachim Pileborg我开始使用/了解占位符和绑定。

现在我要发布的是我的实际实现,但概念是相同的。单位= ClassB。 R(aka注册)= ClassA。

调用功能

template<typename Ft> 
unsigned Registration::GetCredits(Ft func) 
{ 
    unsigned sum = 0; 
    for(unsigned i = 0; i < GetSize(); i++) 
    sum += results[i].GetCredits(func(results[i].GetUnit())); 

    return sum; 
} 

Unit& accessTree(std::string id, BSTree<Unit>& tree) 
{ 
    Unit tempU; 
    tempU.SetId(id); 
    return tree.search(tempU); 
} 

在主

R.GetCredits(std::bind(accessTree, _1, std::ref(uTree))); 

未定义参考`无符号整型登记:: GetCredits(STD :: _占位< 1>,的std ::的reference_wrapper>))(STD :: std :: string,BSTree &)>>(std :: _ Bind(std :: _占位符< 1>,std :: reference_wrapper>))(std :: string,BSTree &)>)'|

有点卡在这一点上,我错过了什么?

在此先感谢。

回答

1

有几个问题的解决方案。最明显的是修改getTotal函数和回调函数来接受树作为额外的参数。


另一种解决方案可能是没有真正使用函数指针可言,反而使getTotal模板功能,并通过功能型作为模板参数。然后,您可以使用std::bind将双参数函数传递给getTotal而不是getTotal不真正知道实际的函数类型。

喜欢的东西

template<typename Ft> 
int ClassA::getTotal(Ft func) 
{ 
    ... 
    func(idVec[i]); 
    ... 
} 

使用它像

ClassB& accessTree(const std::string& id, BSTree<ClassB>& tree); 

... 

using namespace std::placeholders; // For `_1` etc. 

BSTree<ClassB> tree; 
a.getTotal(std::bind(accessTree, _1, std::ref(tree))); 

Reference for std::ref

+0

嘿感谢约阿希姆, 我有一个关于占位符和std ::绑定和未读100%确定它做了什么? 你能给出一个很菜鸟的解释吗?或另一个例子? –