When I define a template class,I found that i can't separate the
template class head and the class definition into two files like
defineing a common class. when i trying to do this ,it report error
LNK2019..we can play the probrom back using the code following:
the code divides into three files.
//LinkedList.h
template<typename T>
class LinkedList
{
public:
LinkedList();
~LinkedList();
void clearall();
private:
int*begin;
int listcounter;
};
//////////////////////////
//LinkedList.cpp
#include "LinkedList.h"
template<typename T>
void LinkedList<T>::clearall()
{
}
template <typename T>
LinkedList<T>::~LinkedList()
{
clearall();
}
template<typename T>
LinkedList<T>::LinkedList()
{
begin=0;
listcounter=0;
}
/////////////////////
#define CONSTRUCTING
#include<iostream>
using namespace std;
#include "LinkedList.h"
int main()
{
#ifdef CONSTRUCTING
LinkedList<int> test1;
//LinkedList<int> test2(test1);
#endif
}
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]
But you can, so long as you include the definition in the header.
when i trying to do this ,it report error
> LNK2019..we can play the probrom back using the code following:
> the code divides into three files.
> //LinkedList.h
#ifndef LINKEDLIST_H // Add guard
#define LINKEDLIST_H
> template<typename T>
> class LinkedList
> {
> public:
> LinkedList();
> ~LinkedList();
> void clearall();
> private:
> int*begin;
> int listcounter;
> };
#include "LinkedList.cpp" // Include definition.
#endif
> //////////////////////////
> //LinkedList.cpp
#ifndef LINKEDLIST_CPP // Add guard
#define LINKEDLIST_CPP
> #include "LinkedList.h"
> template<typename T>
> void LinkedList<T>::clearall()
> {
> }
> template <typename T>
> LinkedList<T>::~LinkedList()
> {
> clearall();
> }
>
>
> template<typename T>
> LinkedList<T>::LinkedList()
> {
> begin=0;
> listcounter=0;
> }
#endif
HTH, Louis.
In the general case: Yes you have to. Fopr specific (large) classes,
please see my reply below.
> ...
If you have a ((very) large) templated class and you know beforehand
which types you are going to use with it - or you can just augment the
cpp file if a new type is needed - then you can resolve the unresolved
external linker warnings by adding an explicit template instantiation
for all required types: (LinkedList is rather something where you won't
do this)
// in LinkedList.cpp
template LinkedList<int>;
template LinkedList<unsigned int>;
template LinkedList<std::string>;
// ...
br,
Martin