-1

Mine is an extension of this previous question, How to create a template function within a class? (C++)

I was able to make a function in a class into a template and call it from the main.cpp file. But when I try to do the same by using a separate header and cpp file, the code is not compiling in visual studio.

I get the following error,

Error LNK2019 unresolved external symbol "public: void __cdecl Handler::HandlerFunc(void)" (??$HandlerFunc@H@Handler@@QEAAXXZ) referenced in function main

Working example,

main.cpp

#include <iostream>

class Parent
{
public:
    Parent(){}
    void Print()
    {
        std::cout << "Inside Parent";
    }
    ~Parent(){}
};

class Handler
{
public:
    Handler(){}
    template <class DATATYPE>
    void HandleFunc();
    ~Handler(){}
};

template <class DATATYPE>
void Handler::HandleFunc() 
{
    Parent *parent = new DATATYPE();
    parent->Print();
}

int main()
{
    Handler *h = new Handler();
    h->HandleFunc<Parent>();
}

Error code, (same code as above split into multiple files)

Handler.h

class Handler
{
public:
    Handler(){}
    template <class DATATYPE>
    void HandleFunc();
    ~Handler(){}
};

Handler.cpp

template <class DATATYPE>
void Handler::HandleFunc() 
{
    Parent *parent = new DATATYPE();
    parent->Print();
}

Main.cpp

int main()
{
    Handler *h = new Handler();
    h->HandleFunc<Parent>();
}
Pat. ANDRIA
  • 2,207
  • 1
  • 10
  • 25

0 Answers0