Linker error with templatized function

B

Bob Altman

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!)
 
B

Bob Altman

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.
 
I

ismailp

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
 
G

Greg Comeau

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?

http://www.comeaucomputing.com/techtalk/templates/#whylinkerror
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Top