【发布时间】:2017-05-30 22:51:32
【问题描述】:
大家好,我正在创建一个 List 类,以便能够像在 python 中一样操作数据,但在 c++ 中。 我想出了一个主意。基本上是一种遍历每个节点的方法,如果满足特定条件则将其删除。但我希望该条件由库的用户确定,因此我实现了一个指向 bool 函数的指针,该函数将一个模板数据(与 List 相同的类型)作为其唯一参数。
到目前为止,我设法运行了这个......
.h 文件:
int delIf(bool (*)(T));
.cpp 文件:
template <typename T>
int List<T>::delIf(bool (*ptr)(T)){
int tot=0;
T aux;
for (int i=0;i<tam;i++)
{
aux=(*this)[i]; //Ive overloaded the [], and it works fine
if ((*ptr)(aux))
{
tot++;
this->del(i);
}
}
return tot;
}
main.cpp:
#include <iostream>
#include "lists.cpp"
using namespace std;
bool check(int);
int main()
{
List<int> a;
for (int i=0;i<10;i++)
a.push(i);
a.delIf(&check);
return 0;
}
bool check(int a){
if (a%2==0)
return true;
else
return false;
}
这很好用,但是,我想知道是否可以重载 delIf 方法,以便它不将指向函数的指针作为参数,而是对它的引用,因此库的用户可以调用:
delIf(check); //No '&' required
而不是
delIf( & check);
目前这是强制性的。我尝试将原型更改为:
int delIf( (bool (*)(T)) & );
但我不断收到错误。
在此先感谢大家。
【问题讨论】:
-
“一种遍历每个节点的方法,如果满足特定条件则将其删除。但我希望该条件由用户确定”-听起来您正在重新发明
std::remove_if- en.cppreference.com/w/cpp/algorithm/remove -
你的
check函数可以写成更简单的return a % 2 == 0;。
标签: c++ pointers reference function-pointers pass-by-reference