C++ 缺少类模板的参数列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15283195/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Argument list for class template is missing
提问by user2146215
I'm having a curious issue, and I'm not quite sure what the issue is. I'm creating a class called LinkedArrayList that uses a typename template, as shown in the code below:
我有一个奇怪的问题,我不太确定问题是什么。我正在创建一个名为 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);
};
Now, this doesn't give any errors or problems. However, creating the functions in the .cpp file gives me the error "Argument list for class template 'LinkedArrayList' is missing." It also says that ItemType is undefined. Here is the code, very simple, in the .cpp:
现在,这不会产生任何错误或问题。但是,在 .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;}
It looks like it has something to do with the template, because if I comment it out and change the ItemTypes in the functions to ints, it doesn't give any errors. Also, if I just do all the code in the .h instead of having a separate .cpp, it works just fine as well.
看起来它与模板有关,因为如果我将其注释掉并将函数中的 ItemTypes 更改为 ints,它不会给出任何错误。另外,如果我只是在 .h 中执行所有代码而不是单独的 .cpp,它也可以正常工作。
Any help on the source of the problem would be greatly appreciated.
任何有关问题根源的帮助将不胜感激。
Thanks.
谢谢。
回答by Andy Prowl
First of all, this is how you should provide a definition for member functions of a class template:
首先,这是您应该如何为类模板的成员函数提供定义:
#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;}
Secondly, those definitions cannot be put in a .cpp
file, because the compiler won't be able to instantiated them implicitly from their point of invocation. See, for instance, this Q&Aon StackOverflow.
其次,这些定义不能放在.cpp
文件中,因为编译器无法从它们的调用点隐式实例化它们。例如,参见StackOverflow 上的这个问答。