简体   繁体   中英

Accessing Binary Search Tree in a Function

Consider the following code:

#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.
}

The operators of ClassB have been overloaded. Consider id it's primary key if you will.

**Edit So Thanks to Joachim Pileborg I've started to use/ learn about placeholders and binding.

Now what I'm about to post is my actual implementation but the concepts are the same. Unit = ClassB. R(aka Registration) = ClassA.

Calling Function

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);
}

In main

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

undefined reference to `unsigned int Registration::GetCredits(std::_Placeholder<1>, std::reference_wrapper >))(std::string, BSTree&)> >(std::_Bind(std::_Placeholder<1>, std::reference_wrapper >))(std::string, BSTree&)>)'|

A little stuck at this point, what have I missed?

Thanks in advance.

There are a couple of solutions to your problems. The most obvious is of course to modify both the getTotal function and the callback function to accept the tree as an extra argument.


Another solution might be to not really use function pointers at all, but to make getTotal a template function, and pass the function type as the template argument. Then you could use std::bind to pass a two-argument function to the getTotal without getTotal not really knowing about the actual function type.

Something like

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

Use it like

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 )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM