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

3
  • Including the errors in your question would allow a more accurate response. Sep 20, 2010 at 14:14
  • Related : Also read this answer. Sep 20, 2010 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. Sep 20, 2010 at 14:17

1 Answer 1

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() {};    
}; 
1
  • 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). Sep 20, 2010 at 16:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.