Hi all,
This is the first time I've tried to create a templatized function, and I
can't get past a linker error. I create a new, unmanaged C++ application
and added a class named MyClass. In MyClass.h I added:
template <class T> void MyFunc(T);
In MyClass.cpp I added:
template <class T> void MyClass::MyFunc(T)
{
cout << T << endl;
}
In the main program, I added:
MyClass t;
t.MyFunc(25);
When I build the project, the compiler is happy, but the linker says:
Unresolved external symbol "public: void __thiscall
MyClass::MyFunc<int>(int)"
What have I missed?
(BTW, I just want to take a moment to thank the good folks who have been
answering my many questions in the NG recently. You guys are great!)
Bob Altman - 14 Mar 2005 16:55 GMT
I found the applicable section in my trusty "Ivor Horton's Beginning C++",
which points out that templates are best implemented entirely in the header
file; moreover, if the implementation is in a separate cpp file then an
"export" keyword needs to be inserted somewhere in the syntax, although it's
not clear where to apply that keyword. In any event, this code needs to be
reasonably portable, and Mr. Horton points out that "export" is not widely
implemented so... I'll put my implementation in the header file and be done
with it.
> Hi all,
>
[quoted text clipped - 24 lines]
> (BTW, I just want to take a moment to thank the good folks who have been
> answering my many questions in the NG recently. You guys are great!)
ismailp - 15 Mar 2005 00:26 GMT
this is called "exporting". however, as far as I know, only one
compiler on the earth implemented standard's that facility (Comeau). As
of Visual Studio .NET 2003, compiler does this, but without export
keyword.
Implementing template in header is harmless, and clearer; the more
template arguments you have, the more complex code you deal with. The
simplest function declaration in a .cpp file would take longer.
Ismail
Greg Comeau - 15 Mar 2005 01:12 GMT
>Hi all,
>
[quoted text clipped - 21 lines]
>
>What have I missed?
http://www.comeaucomputing.com/techtalk/templates/#whylinkerror

Signature
Greg Comeau / Comeau for the Mac? Stay tuned.
Comeau C/C++ ONLINE ==> http://www.comeaucomputing.com/tryitout
World Class Compilers: Breathtaking C++, Amazing C99, Fabulous C90.
Comeau C/C++ with Dinkumware's Libraries... Have you tried it?