0

I am trying to write class based on singleton design pattern which contain std::map as value.

  //Data.h
    #ifndef Data_h
#define Data_h

// from std
#include<map> 


using namespace std;

template <typename T>

class Data
{
 private:
  Data();
  virtual ~Data();
  map<string,T >* value_map;
  static Data<T> *m_data;

 public:
  //list of method
  static Data<T>*  instance()
{
  if (NULL == m_data){
    m_data=new Data;
  }
  return m_data;
}
  virtual T getValue(string name);
  virtual void insert(string name, T value);
  //virtual void finish();
  // member field

};
#endif
   // Data.cpp

    #include"Data.h"
#include<iostream>

//implementation of class data
//which is based on singleton pattern design

template <typename T>
Data<T>::Data()
{
  value_map=new map<string, <T> >();
}


template <typename T>
Data<T>::~Data()
{ 
}



template <typename T>
T Data<T>::getValue(string name)
{
  return value_map[name];
}

template <typename T>
void Data<T>::insert(string name,T value)
{
  typedef map<string, typename T> mapa;
  value_map->insert(typename mapa::value_type(name,value));
} 

But unfortunately this code doesn't compile. What I should change to be able to insert value into map. Best regards.


I have merged the .cpp and the .h files. Currently code looks like this.

#ifndef Data_h
#define Data_h

// from ROOT-  nie wiem jak zrobic 
#include<map> 
#include<string>


using namespace std;

template <typename T>

class Data
{
 private:
  Data();
  virtual ~Data();
  map<string,T > *value_map;
  static Data<T> *m_data;

 public:
  //list of method
  static Data<T>*  instance()
{
  if (NULL == m_data){
    m_data=new Data;
  }

  return m_data;
}
  virtual T getValue(string name);
  virtual void insert(string name, T value);
  //virtual void finish();


};

template <typename T>
Data<T>::Data()
{
  value_map=new map<string, T>();
};


template <typename T>
Data<T>::~Data()
{ 
};

template <typename T>
T Data<T>::getValue(string name)
{
  return value_map[name];
};

template <typename T>
void Data<T>::insert(string name,T value)
{

   typedef map<string, T > mapa;
  value_map->insert( mapa::value_type(name,value));
};


#endif

But steal it doesn't compile. What should I do to fix my class. Especially method insert return compilation error. I look forward to hearing from you.

Andrew Barber
  • 39,603
  • 20
  • 94
  • 123
user1877600
  • 627
  • 1
  • 9
  • 26
  • possible duplicate of [Splitting templated C++ classes into .hpp/.cpp files--is it possible?](http://stackoverflow.com/questions/1724036/splitting-templated-c-classes-into-hpp-cpp-files-is-it-possible) – billz Jan 18 '13 at 04:58

1 Answers1

1

You are using template, you can't separate code into header(.h) and source(.cpp), to make your code work, make Data.h contain all code or add include directive to the end of Data.h file.

#include Data.cpp
billz
  • 44,644
  • 9
  • 83
  • 100