I’m trying to write a derived class of STL set<> and a link error occurred.
Header file Set.h:
#pragma once
#include <set>
using namespace std;
template <class Ty>
class Set : public set<Ty> {
public:
Set(void);
virtual ~Set(void);
};
Auxiliary source file Set.cpp:
#include "Set.h"
template <class Ty>
Set<Ty>::Set(void) {}
template <class Ty>
Set<Ty>::~Set(void) {}
Main program:
#include <iostream>
#include "../myLibrary/Set.h"
#pragma comment(lib, "../x64/Debug/myLibrary.lib")
using namespace std;
int main() {
Set<int> s;
s.insert(1); s.insert(2); s.insert(3);
for(Set<int>::const_iterator it = s.begin(); it!=s.end(); it++)
wcout << *it << endl;
return 0;
}
This raises
Set.obj : *warning* LNK4221:
and
_Entry_myLibrary_TEST.obj :error LNK2019: "public: virtual __cdecl Set<int>::~Set<int>(void)" (??1?$Set@H@@UEAA@XZ)
Your immediate problem is putting the template functions in Set.cpp.
Template functions need to be visible to the code that uses them so they need to be in the .h file not in a separate .cpp file.
Auxiliary source file Set.cpp:
Put the functions into the header, they need to be visiable where they are used.
I’ll leave it to others to point out why inheriting from set is probably not what you want to do as it’s not your question.