0

i created a template that contains a map. when i try to create an instance of that template i encounter a linking problem with the constructor and destructor. also, when i try to create an instance in main it skips the line while debugging, and doesn't even show it in the locals list. it doesn't compile "DataBase db;" unless i add "()" after db. (that's the way i try to initiate the instance in main).

the code:

h:

template <class keyVal,class searchVal, class T>  
class DataBase  
{  
private:  
    map<keyVal,pair<searchVal,T*>*> DB;  
public :  
    DataBase();  
    virtual ~DataBase();    
}; 

cpp:

#include "DataBase.h"  

template <class keyVal,class searchVal, class T>  
DataBase<keyVal,searchVal,T>::DataBase()  
{}  

template <class keyVal,class searchVal, class T>  
DataBase<keyVal,searchVal,T>::~DataBase()  
{}

thanks

Steve Townsend
  • 53,498
  • 9
  • 91
  • 140
shiran bar
  • 29
  • 2
  • 8
  • Including the errors in your question would allow a more accurate response. – Steve Townsend Sep 20 '10 at 14:14
  • Related : Also read [this](http://stackoverflow.com/questions/3749099/why-should-the-implementation-and-the-declaration-of-a-template-class-be-in-the-s/3749115#3749115) answer. – Prasoon Saurav Sep 20 '10 at 14:15
  • 1
    Don't write `Database db();` to make a database. It doesn't do that, but declares a function that returns one instead. – Mike Seymour Sep 20 '10 at 14:17

1 Answers1

5

Add the implementation of template classes (and functions) directly in the header file:

template <class keyVal,class searchVal, class T>  
class DataBase  
{  
private:  
    map<keyVal,pair<searchVal,T*>*> DB;
public :  
    DataBase() {};  
    virtual ~DataBase() {};    
}; 
John Dibling
  • 99,718
  • 31
  • 186
  • 324
  • Nit-pick: shouldn't have a semicolon after a function definition :-). Worth noting that this requests inlining of the functions, that they can also be defined beneath the class to avoid that, and that some people actually include a cpp file from a header to allow more uniformity of style with non-templated code (though that's not particularly common and I'm not recommending it). – Tony Delroy Sep 20 '10 at 16:13