错误:没有用于调用函数指针的匹配函数

时间:2018-04-04 19:22:23

标签: c++

我创建了一个模板化的BST,其功能是收集数据:

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

然后在另一个类中,我尝试使用此数据结构对另一个类的对象进行排序。我无法从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);
}

其他所有测试都没有问题。只有这不起作用。错误消息是:

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&)}'|

有人可以告诉我哪里出错吗?

1 个答案:

答案 0 :(得分:1)

BST::func被声明为指向独立函数的指针,但是在调用inorderCollectionTraversal(collectData)时,您试图传递一个类方法。如果collectData()未声明为static(您的代码暗示,假设collectorQuery的非静态成员),那么这将无效,因为{{ 1}}有一个隐含的collectData()参数,this在调用时不会填充。

请考虑将func改为使用std::function

func

然后你可以使用lambda来调用std::function<void(T&)> func;

collectData()

甚至直接推入...->second.inorderCollectionTraversal([this](Weather &w){ collectData(w); });

collector
相关问题