[英]“Function” is not a type C++
我想制作一個模板類,並將其傳遞給比較函數。 我在此鏈接上找到了一個很好的答案
不幸的是,當我創建一個名為“ WaitingQueue”的模板類並在該類的構造函數中(在foo類中)傳遞了compare函數時,代碼無法編譯並引發錯誤:“'compare'不是一種類型”。
我無法理解這里的錯誤。 上面鏈接中的代碼運行無誤。 誰能告訴我我做錯了什么嗎? 提前致謝
#include <stdint.h>
#include <stddef.h>
#include <string.h>
enum { OK, ERROR };
template <class T>
class WaitingQueue
{
struct QueueElement
{
public:
T data;
QueueElement *next;
QueueElement(T *pdata): next(0)
{
memcpy(&data, pdata, sizeof(T));
}
};
QueueElement *head, tail;
public:
bool (*comparefunc)(uint16_t, T*);
WaitingQueue (bool (*compareFunction)(uint16_t, T*)) :comparefunc(compareFunction), head(0), tail(0) { }
int search(int16_t id, T *ret_data)
{
QueueElement *temp = head;
QueueElement *prev = 0;
if (temp != NULL)
{
if (comparefunc(id, &temp->data) == true)
{
if (prev)
{
prev->next = temp->next;
}
else
{
head = head->next;
}
memcpy(ret_data, &temp->data, sizeof(temp->data));
delete temp;
return OK;
}
prev = temp;
temp = temp->next;
}
return ERROR;
}
};
typedef struct _cmd
{
uint8_t flags;
uint16_t id;
} cmd;
bool compare(uint16_t id, cmd *cmd)
{
return (cmd->id == id);
}
class foo
{
WaitingQueue<cmd> queue(compare);
};
這是通常的令人討厭的解析。 WorkingQueue<cmd> queue(compare);
編譯器將其理解為聲明為queue
的方法的聲明,該方法返回WorkingQueue<cmd>
並獲取不存在的類型compare
的對象。 您可以理解,這意味着要使用花括號初始化來聲明使用compare
函數初始化的字段 :
WaitingQueue<cmd> queue{compare};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.