缺少类模板的参数列表

时间:2013-03-07 22:38:43

标签: c++ templates typename

我有一个好奇的问题,我不太清楚问题是什么。我正在创建一个名为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,它也可以正常工作。

非常感谢任何有关问题根源的帮助。

感谢。

1 个答案:

答案 0 :(得分:17)

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

#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文件中,因为编译器无法从它们的调用点隐式地实例化它们。例如,请参阅this Q&A on StackOverflow

相关问题