chpicker
Programmer
- Apr 10, 2001
- 1,316
This isn't specific to VC++ but appears to be a general C++ issue. I'm trying to learn how to use templates properly. I've run into a strange problem, though.
Take the following program:
This program compiles and links just fine. However, what I want to do is split the program into 3 files: one header and source file for the classes and one source file for the main function. This division would look like this.
This program also compiles just fine. However, when it links, I get unresolved externals on all of the template functions that get used, including the constructor and destructor.
I rewrote the class.cpp and class.h files, removing the template indicators and changing any "T" references to "test". It compiles and links just fine.
What am I missing? What do I need to do differently when I use templates if I want to be able to organize my source code into multiple files?
Ian
Take the following program:
Code:
#include <iostream.h>
class test {
public:
int theNum;
};
template <class T>
class mine {
public:
mine();
~mine();
T* thePointer;
T* GetPointer();
};
template <class T>
mine<T>::mine():thePointer(NULL) {}
template <class T>
mine<T>::~mine() {if (thePointer) delete thePointer;}
template <class T>
T* mine<T>::GetPointer() {return thePointer;}
void main() {
test MyTest;
MyTest.theNum=5;
mine<test> excalibur;
excalibur.thePointer=new test;
(excalibur.GetPointer())->theNum=6;
cout << "MyTest.theNum is " << MyTest.theNum << endl;
cout << "excalibur's num is " << excalibur.thePointer->theNum << endl;
}
Code:
// class.h
#ifndef __CLASS_H__
#define __CLASS_H__
class test {
public:
int theNum;
};
template <class T>
class mine {
public:
mine();
~mine();
T* thePointer;
T* GetPointer();
};
#endif
Code:
// class.cpp
#include "class.h"
template <class T>
mine<T>::mine():thePointer(NULL) {}
template <class T>
mine<T>::~mine() {if (thePointer) delete thePointer;}
template <class T>
T* mine<T>::GetPointer() {return thePointer;}
Code:
// main.cpp
#include <iostream.h>
#include "class.h"
void main() {
test MyTest;
MyTest.theNum=5;
mine<test> excalibur;
excalibur.thePointer=new test;
(excalibur.GetPointer())->theNum=6;
cout << "MyTest.theNum is " << MyTest.theNum << endl;
cout << "excalibur's num is " << excalibur.thePointer->theNum << endl;
}
I rewrote the class.cpp and class.h files, removing the template indicators and changing any "T" references to "test". It compiles and links just fine.
What am I missing? What do I need to do differently when I use templates if I want to be able to organize my source code into multiple files?
Ian