【问题标题】:error: no matching function for call for function pointer错误:没有匹配的函数调用函数指针
【发布时间】:2018-04-04 19:22:22
【问题描述】:

我创建了一个具有收集数据功能的模板化 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);
}

其他一切都经过测试,没有问题。只有这样是行不通的。错误信息是:

没有匹配函数调用 'BST::inorderCollectionTraversal() 候选人: void BST::inorderCollectionTraversal(BST::func) const [with T 错误:没有匹配函数调用 'BST::inorderCollectionTraversal()'| include\BST.h|235|注意:候选:void BST::inorderCollectionTraversal(BST::func) const [with T = MetData; BST::func = void (*)(MetData&)]| include\BST.h|235|注意:没有已知的参数 1 从 '' 到 'BST::func {aka void (*)(MetData&)}'的转换|

谁能告诉我哪里出错了?

【问题讨论】:

标签: c++


【解决方案1】:

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

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

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

然后您可以使用 lambda 调用 collectData()

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

甚至直接推入collector

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

【讨论】:

  • 感谢您的意见。我用你的建议试过了,但它会产生更多指向 std:: 的错误
  • 您是否使用 C++11 或更高版本进行编译?您是否在代码中添加了#include &lt;functional&gt;
猜你喜欢
  • 1970-01-01
  • 2013-05-05
  • 2015-08-03
  • 2012-12-28
  • 2015-03-31
  • 1970-01-01
  • 2020-06-09
相关资源
最近更新 更多