什么是 void (*op)(T &) 和 void (*op)(T &, void *)?

Daa*_*uro 3 c++ parameters templates linked-list

我有一个关于链表和模板的作业,其中有一些带有奇怪参数的函数是强制性的。我找不到有关它的在线文档,并且感谢任何提供的材料。

我尝试为 op 分配另一个地址,然后它编译得很好,但我无法调用它。

template <class T> struct L1Item {
  T data;
  L1Item<T> *pNext;
  L1Item() : pNext(NULL) {}
  L1Item(T &a) : data(a), pNext(NULL) {}
};

template <class T> class L1List {
  L1Item<T> *_pHead; // The head pointer of linked list
  size_t _size;      // number of elements in this list
public:
  void traverse(void (*op)(T &)) {
    // TODO: Your code goes here
  }
  void traverse(void (*op)(T &, void *), void *pParam) {
    // TODO: Your code goes here
    //    string *Req = static_cast<string *>(pParam);
    //    if (*Req == "find city's id") {
    //        op = this->_pHead;
    //    };
  }
};
Run Code Online (Sandbox Code Playgroud)

Adr*_*ica 6

该代码void (*op)(T &)声明op为一个指向函数的指针,该函数将以对类型的引用T作为参数;void (*op)(T &, void *)类似,但有一个额外的类型参数void*

您应该调用传递的函数,而不是尝试在(注释掉的)代码中将指向对象的指针分配给它。像这样的事情,例如:op = this->_pHead;

void traverse(void (*op)(T &, void *), void *pParam) {
// TODO: Your code goes here
    op(pHead->data, pParam); // First parameter is a T passed by reference
}
Run Code Online (Sandbox Code Playgroud)

在代码的其他地方,当您实际调用 traverse时,您需要给出您(或某人)定义的函数(的地址)作为其第一个参数;例如:

template <class T> void myFunc(T& obj, void *pParam) {
    string *Req = static_cast<string *>(pParam);
    if (*Req == "find city's id") {
    // do something with/to "obj"
    }
}
//...
traverse(myFunc, pString);
// ...
Run Code Online (Sandbox Code Playgroud)

请随意要求进一步的解释(但也要阅读您问题中给出的评论)!