1

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)

Gilles 'SO- stop being evil'
  • 104,111
  • 38
  • 209
  • 254
Jeffrey Goines
  • 935
  • 1
  • 11
  • 30
  • 1
    possible duplicate of [Why can templates only be implemented in the header file?](http://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file) – Mat Aug 09 '12 at 09:52
  • 3
    As a side note, std:: containers are not designed to be inherited from. You will probably be better off using composition than trying to extend them. – Mat Aug 09 '12 at 09:53
  • possible duplicate of [Why do I get "unresolved external symbol" errors when using templates?](http://stackoverflow.com/questions/456713/why-do-i-get-unresolved-external-symbol-errors-when-using-templates) – Bo Persson Jan 23 '13 at 21:34

1 Answers1

1

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:

#include "Set.h" 
template <class Ty> 
Set<Ty>::Set(void) {} 

template <class Ty> 
Set<Ty>::~Set(void) {} 

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.

jcoder
  • 29,554
  • 19
  • 87
  • 130