大家好,我正在创建一个 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);
这是目前强制性的。我尝试将原型(prototype)更改为:
int delIf( (bool (*)(T)) & );
但我不断收到错误。
在此先感谢大家。
最佳答案
你的前提是错误的。您不需要在函数前面添加 &
即可将其传递给 delIf
。函数名几乎在表达式中使用的所有地方都会退化为指向该函数的指针。 (包括你调用函数的时候!)事实上,它唯一没有的地方是当它被用作 &
的参数时 - 所以
func
&func
具有完全相同的类型和值。
话虽如此,是的,您可以传递引用。函数指针的第一条规则 - 写一个 typedef
typedef bool pred_t(T);
void delIf( pred_t& pred );
但是!我强烈建议您将 delIf
编写为函数模板,并允许任何可以用 T
调用的东西,并且具有可以隐式转换为 的函数结果> bool
。
template <typename Pred>
void delIf(Pred pred) {
...
}
这将允许用于捕获 lambda 和一般的仿函数。
还有,你说的这个CPP文件是什么?模板必须在头文件中实现。查看 this question 的答案.
(注意:“Pred”是“predicate”的缩写,标准称其为此类函数。)
关于c++ - 引用函数指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41670644/