导致以下函数错误的 c++ 模板

c++ Templates causing errors with function below

本文关键字:c++ 模板 错误 函数      更新时间:2023-10-16

>我刚刚开始学习C ++,我一直试图弄清楚为什么我会遇到这个问题,在使用标准数据结构(使用int)之前代码工作正常,但是一旦我尝试使用模板反而遇到了问题

希望我在正确的部分发布了这个,如果需要,我会发布更多代码

83    template <class  t>
84    struct node
85    {
86        t number  ;
87        node *next ;
88   };
89   
90   bool isEmpty(node *head)
91   {
92      if (head == NULL)
93      {
94         return true;
95       }
96       else
97       {
98           return false;
99       }
100   }

错误我得到.

91|error: missing template arguments before '*' token|
91|error: 'head' was not declared in this scope| 
92|error: expected ',' or ';' before '{' token|
 ||=== Build finished: 3 errors, 0 warnings (0 minutes, 0 seconds) ===|

感谢我得到的任何反馈:)

你需要 s.th,比如:

template<class t>
bool isEmpty(node<t> *head) ...

note是一个模板,你需要用一个类型来实例化它,比如

bool isEmpty(node<int> *head)
{
  return head == NULL; // compare to if/else, this is much neater, right?
}

isEmpty模板函数

template<typename T>
bool isEmpty(node<T> *head)
{
  return head == NULL;
}