Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Template does not work when it is not in the main class

I have tried using a template in a class but it works in the main function.

Here is my main function:

#include <iostream>
#include <string>

using namespace std;

int main() {
    templEx();
}

And here is the class where the template is located:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#include <iostream>

#include <string>

using namespace std;

template<typename T>
void Print(T value)
{
    std::cout << value << std::endl;
}

void templEx() {
    Print("Venezuela");
}

And here are the errors which I get:

Severity Code Description Project File Line Source Suppression State
Error LNK2005 "void __cdecl templEx(void)" (?templEx@@YAXXZ) already defined in AddSubtract.obj ConsoleApplication1 C:\Users\bahge\source\repos\ConsoleApplication1\ConsoleApplication1\Source1.obj 1 Build

Severity Code Description Project File Line Source Suppression State
Error LNK1169 one or more multiply defined symbols found ConsoleApplication1 C:\Users\bahge\source\repos\ConsoleApplication1\x64\Debug\ConsoleApplication1.exe 1 Build

>Solution :

You’re compiling that code that defines tmplEx once in the main.cpp and additionally in the secondary source file, which leads to the conflict.

Define the template in a separate header file that both can #include as necessary.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading