Chung ZH
Chung ZH

Reputation: 11

error: no matching function for call for function pointer

I created a templated BST with function to collect data:

typedef void (*func)(T&);

...

template<class T>
void BST<T>::inorderCollectionTraversal(func f) const
{
    inorderCollection(root,f);
}

template<class T>
void BST<T>::inorderCollection(node<T> *p, func f) const
{
    if(p!=NULL){
        inorderCollection(p->leftPtr, f);
        f(p->data);
        inorderCollection(p->rightPtr, f);
    }
}

And then in another class, I tried to use this data structure to sort objects of another class. I am unable to extract the objects from the BST:

map<string, BST<Weather> > dataByMonth;

dataByMonth.find(monthCount[i]+eYear)->second.inorderCollectionTraversal(collectData); // the error points to this line

void Query::collectData(Weather& w){
    collector.push_back(w);
}

Everything else was tested with no issue. Only this is not working. The error message is :

No matching function for call to 'BST<Weather>::inorderCollectionTraversal(<unresolved overloaded function type>)

candidate: void BST<T>::inorderCollectionTraversal(BST<T>::func) const [with T

error: no matching function for call to 'BST<MetData>::inorderCollectionTraversal(<unresolved overloaded function type>)'|
include\BST.h|235|note: candidate: void BST<T>::inorderCollectionTraversal(BST<T>::func) const [with T = MetData; BST<T>::func = void (*)(MetData&)]|
include\BST.h|235|note:   no known conversion for argument 1 from '<unresolved overloaded function type>' to 'BST<MetData>::func {aka void (*)(MetData&)}'|

Can anyone advise where I went wrong?

Upvotes: 0

Views: 998

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 596256

BST::func is declared as a pointer to a standalone function, but you are trying to pass it a class method when calling inorderCollectionTraversal(collectData). If collectData() is not declared as static (which your code implies, assuming collector is a non-static member of Query), then this will not work, as collectData() has an implicit this parameter that func does not populate when called.

Consider changing func to use std::function instead:

std::function<void(T&)> func;

And then you can use a lambda to invoke collectData():

...->second.inorderCollectionTraversal([this](Weather &w){ collectData(w); });

Or even just push into collector directly:

...->second.inorderCollectionTraversal([&](Weather &w){ collector.push_back(w); });

Upvotes: 1

Related Questions