djones7936
Programmer
Does anybody know why template code will not compile unless the class declaration and actual class code is in the same file? In other words, if I separate the class into two files .h(header) and .cpp (source file), the code does not run.
Here is an example of that I'm talking about. I've tried the code with VC++ 6.0 and 7.0, as a Blank Windows Console program.
My error message is:
I can't believe this isn't working! I made a really elaborate class using template but it wouldn't compile unless all the code for the class was in one file. I don't understand why this code wouldn't work.
Does anyone have insight as to why C++ was designed this way, or if there is something I'm overlooking?
Thanks, -Dave
Here is an example of that I'm talking about. I've tried the code with VC++ 6.0 and 7.0, as a Blank Windows Console program.
Code:
// In "DSRGB24.h"
template <class T>
class CRGB24
{
private:
T m_R;
T m_G;
T m_B;
public:
CRGB24();
};
// In "DSRGB24.cpp"
#include "DSRGB24.h"
template <class T>
CRGB24<T>::CRGB24()
{
m_R = 0;
m_G = 0;
m_B = 0;
}
//In main.cpp
#include "DSRGB24.h"
int main()
{
CRGB24<int> iRGB1;
CRGB24<int> iRGB2;
return 0;
}
Code:
Compiling...
DSRGB24.cpp
Linking...
main.obj : error LNK2001: unresolved external symbol "public: __thiscall CRGB24<int>::CRGB24<int>(void)" (??0?$CRGB24@H@@QAE@XZ)
trash___Win32_Debug/trash.exe : fatal error LNK1120: 1 unresolved externals
Error executing link.exe.
trash.exe - 2 error(s), 0 warning(s)
Does anyone have insight as to why C++ was designed this way, or if there is something I'm overlooking?
Thanks, -Dave