简体   繁体   English

“函数”不是C ++类型

[英]“Function” is not a type C++

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". 不幸的是,当我创建一个名为“ WaitingQueue”的模板类并在该类的构造函数中(在foo类中)传递了compare函数时,代码无法编译并引发错误:“'compare'不是一种类型”。

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 . 编译器将其理解为声明为queue的方法的声明,该方法返回WorkingQueue<cmd>并获取不存在的类型compare的对象。 You can make it understand that you mean to declare a field initialized with the compare function by using braces initialization: 您可以理解,这意味着要使用花括号初始化来声明使用compare函数初始化的字段

WaitingQueue<cmd> queue{compare};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM