class MyClass
	template <class T>
	static void Swap(T& Var1, T& Var2);


template <class T>
void MyClass::Swap( T& Var1, T& Var2 )
	Var1 ^= Var2;
	Var2 ^= Var1;
	Var1 ^= Var2;

In another file

#include "MyClass.h"
int n = 40;
int m = 60;

This code gives this error:

Error 1 MyClassCallee.obj error LNK2019: unresolved external symbol "public: static void __cdecl MyClass::Swap<int>(int &,int &)" (??$Swap@H@MyClass@@SAXAAH0@Z) referenced in function "protected: void __thiscall MyClassCallee::SwapTest(void)" (?SwapTest@MyClassCallee@@IAEXXZ)

I'm lost, what can I do to correct this error?

Recommended Answers

All 4 Replies

Just place the template outside the class:

Outside the class? What's that supposed to mean?

Member prototype is inside the class body, and the definition is in a separate file. Isn't this formation what it has to be?

Not for template functions (and classes).

A template function are the instructions to the compiler on how to write the function given the parameter types... the template of the function.

When the compiler compiles your code and sees a call to a template function it looks up the template function and uses it to create an actual function that it compiles into the object for the file.

However the compiler works on a single file at a time. If the template function is not defined somewhere in the file being compiled the compiler can not create a real function from the template when it sees the function call because it can not see the template.

So the definition of the template function needs to be visible to the compiler when it is compiling your file there are 2 ways of doing this

  1. Put the definitions of the template functions in the header.

  2. Put the definitions of the template functions in a different file, NOTE not a cpp file because best practice is not to include cpp files, and then include that file into the header.

Whatever you do at the time the compiler sees the template function call it must have already seen the definition of the template.

commented: Thank you for the explanation. +4

Thank you for the explanation.
I understand the issue now.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.