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:
#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:
#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.
Any help on the source of the problem would be greatly appreciated.
Thanks.
Can default arguments be used with the template class? Explanation: The template class can use default arguments.
Templates are a feature of the C++ programming language that allows functions and classes to operate with generic types. This allows a function or class to work on many different data types without being rewritten for each one.
A template allows us to create a family of classes or family of functions to handle different data types. Template classes and functions eliminate the code duplication of different data types and thus makes the development easier and faster. Multiple parameters can be used in both class and function template.
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&A on StackOverflow.
While providing the definition, if you are using template also mention them with your class
#include "LinkedArrayList.h"
template<typename ItemType>
void LinkedArrayList<ItemType>::insert (int index, const ItemType& item)
{}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With