Click here to Skip to main content
15,891,711 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,
I was trying to make a generic contiguous list. Here's the code from List.h and List.cpp. In List.cpp below, I have only shown the constructor where the error is happening. When I define List < int > the_list in main(), I get an error "Undefined reference to List<int>::List()".

List.h
const int maxlist=1000;
enum Error_code
{
    success,
    overflow,
    underflow,
    range_error
};
template <class List_entry>
class List
{
    public:
    List();
    bool empty();
    bool full();
    int size();
    Error_code insert(int position, const List_entry &x);
    Error_code retrieve(int position, List_entry &x)const;
    Error_code replace(int position, const List_entry &x);
    Error_code remove(int position, List_entry &x);
    void traverse(void (*visit)(List_entry &x));//*visit is the pointer to function which performs operation on list
    protected:
    int count;
    List_entry entry[maxlist];
};


List.cpp
#include"List.h"
template <class List_entry>
List<List_entry>::List()
{
    count=0;
}
Posted

1 solution

when you are using template classes you need to put the function implementations in also in the header file.Otherwise you need to explicitly declare class for each type in cpp file. This is the case with visual studio. i don't know how its on GCC or other compilers.

anyway give it a try by moving function implementations to header file :)
 
Share this answer
 
Comments
Henry Minute 31-Dec-10 11:56am    
You know, a code snippet showing the correct way, would really have made this clear for the OP and others.
jk chan 31-Dec-10 12:13pm    
But there is nothing more to be shown, he just need to put that constructor to header file. :)
Do you think my words are unclear ?
jean Davy 31-Dec-10 14:24pm    
And this is why template libraries are only made of header files ! Better in your exe you will have only "templated" code you use. Think of C++ templates as a way to generate C++ code.
optimus_prime1 31-Dec-10 14:31pm    
@jk chan: I tried to put function and implementations both in one file but its giving too many errors.
Here's the code of List.h -> http://pastebin.com/kJkuzXRV
And here's the code of main.cpp -> http://pastebin.com/8hyiGtqi
Btw, I am trying a Win32 console on Code::Blocks
T2102 1-Jan-11 7:56am    
From your file: List() { count=0; }
Comment you should utilize initialization instead of assignment as follows: List() :count(0) {}

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900