I want to make a template class and pass it a compare function. I found a great answer on this link
Unfortunately when I made a template class called "WaitingQueue" and passed the compare function in the constructor of the class(in class foo), the code does not compile and throws error: "'compare' is not a type".
I cannot understand the error here. The code in the link above runs without error. Can anyone please tell me what I have done wrong here? Thanks in advance
#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);
};
This is the usual vexing parse. WorkingQueue<cmd> queue(compare);
is understood by the compiler as the declaration of a method named queue
returning a WorkingQueue<cmd>
and taking an object of the nonexistant type compare
. You can make it understand that you mean to declare a field initialized with the compare
function by using braces initialization:
WaitingQueue<cmd> queue{compare};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.