缺少类模板的参数列表

Argument list for class template is missing

本文关键字:参数 列表      更新时间:2023-10-16

我有一个奇怪的问题,我不太确定是什么问题。我正在创建一个名为LinkedArrayList的类,它使用typename模板,如下面的代码所示:

#pragma once
template <typename ItemType>
class LinkedArrayList 
{
private:
class Node {
    ItemType* items;
    Node* next;
    Node* prev;
    int capacity;
    int size;
};
Node* head;
Node* tail;
int size;
public:
void insert (int index, const ItemType& item);
ItemType remove (int index);
int find (const ItemType& item);
};

现在,这没有给出任何错误或问题。然而,在.cpp文件中创建函数给了我错误"类模板'LinkedArrayList'的参数列表缺失"。它还说ItemType是未定义的。下面是代码,非常简单,在.cpp:

#include "LinkedArrayList.h"
void LinkedArrayList::insert (int index, const ItemType& item)
{}
ItemType LinkedArrayList::remove (int index)
{return ItemType();}
int find (const ItemType& item)
{return -1;}

看起来它与模板有关,因为如果我注释掉它并将函数中的ItemTypes更改为int,它不会给出任何错误。此外,如果我只是在。h中执行所有代码,而不是使用单独的。cpp,它也可以正常工作。

如果您能对问题的根源提供任何帮助,我将不胜感激。

谢谢。

首先,您应该如何为类模板的成员函数提供定义:

#include "LinkedArrayList.h"
template<typename ItemType>
void LinkedArrayList<ItemType>::insert (int index, const ItemType& item)
{}
template<typename ItemType>
ItemType LinkedArrayList<ItemType>::remove (int index)
{return ItemType();}
template<typename ItemType>
int LinkedArrayList<ItemType>::find (const ItemType& item)
{return -1;}

其次,这些定义不能放在.cpp文件中,因为编译器不能从它们的调用点隐式地实例化它们。例如,在StackOverflow上看到这个Q&A

在提供定义的同时,如果您正在使用模板,也要在您的类

中提到它们
#include "LinkedArrayList.h"
template<typename ItemType>
void LinkedArrayList<ItemType>::insert (int index, const ItemType& item)
{}