Re: what about the template error??
- From: "Simon Watson" <simon dot watson at sage dot com>
- Date: Mon, 31 Oct 2005 10:16:22 -0000
"ymsboy" <ymsboy@xxxxxxx> wrote in message
news:%23MAeH0f3FHA.2676@xxxxxxxxxxxxxxxxxxxxxxx
> i created a template class in VC 7 like this:
> ////////////// testTemp.h ///////////
> #pragma once
> using namespace std;
> template<class T,int MAXMIZE>
> class Param{
> public:
> void Print();
>
> };
> ////////////// testTemp.cpp ///////////
> #include "stdafx.h"
> #include "testTemp.h"
> template<class T,int MAXMIZE>
> void Param<T,MAXMIZE>::Print()
> {
> std::cout<< MAXMIZE;
> }
>
> when i used the class like this:
>
> Param<int,67> p;
> p.Print();
>
> i received a link error:
> TempLateTest.obj : error LNK2019: unresolved external symbol "public: void
> __thiscall Param<int,67>::Print(void)" (?Print@?$Param@H$0ED@@@QAEXXZ)
> referenced in function _main
>
> where is my error? please help me!
>
>
I take it that the third section of your posted code is in some other file
that includes testTemp.h.
The problem is that templates are compiled when they are used, as it's only
at that point that the compiler knows the template parameters. The compiler
comes sees testTemp.cpp and will decide that there is nothing to compile
there, and merrily ignore it.
When the compiler comes accross Param<int, 67> p, p.Print(), it's only then
that it knows all the details of the template class that are required. The
trouble is, at that point, the compiler can no longer see the implementation
in testTemp.cpp, so no method body get's compiled and you get the unresolved
symbol.
There are two solutions:
1 - Have the method implementation in the header file (look at the STL
headers, that's how they do it). This makes the implenetation visible to the
compiler at the correct time.
2 - Use explicit template instantiation. This is where you tell the compiler
to create bodies for all functions of the template for certain template
parameters. In your example, you would place the line:
template class Param<int, 67>;
In the .cpp file (I placed it before the implementation, just so you see it
at the top of the file), to tell the compiler to create bodies for all
members of Param<int, 67>, then it'll compile just fine,
Simon
.
- References:
- what about the template error??
- From: ymsboy
- what about the template error??
- Prev by Date: what about the template error??
- Next by Date: Re: STLPort in VC++ - Compile problems
- Previous by thread: what about the template error??
- Index(es):
Relevant Pages
|