ptr_map Problems
#include <string>
#include <boost/ptr_container/ptr_map.hpp>
#include <algorithm>
using namespace std;
using namespace boost;
class abstract_class {
public:
virtual ~abstract_class() {}
virtual int something() = 0;
};
class concrete : public abstract_class {
public:
concrete() : x(0) {} // default ctor needed by ptr_map
concrete(int x) : x(x) {}
virtual int something() { return 8; }
protected:
int x;
};
template<typename Data>
class generic {
public:
generic() : x(0) {} // default ctor needed by ptr_map
generic(Data x) : x(x) {}
Data something() { return x; }
protected:
Data x;
};
typedef generic<int> specialization;
int main() {
// ptr_map<string, abstract_class> abstract_map; // error: cannot instantiate abstract class
int x;
// concrete class
ptr_map<string, concrete> concrete_map;
concrete_map["something"] = * new concrete(4);
concrete & something = concrete_map["something"];
x = concrete_map["something"].something();
// generic class - std::map example
typedef map<string, specialization> generic_map_t;
generic_map_t generic_map;
generic_map["something"] = * new specialization(3);
x = generic_map["something"].something();
generic_map_t::iterator i;
i = generic_map.find("something");
if(i != generic_map.end()) {
specialization s = i->second; // works fine
}
if(generic_map.count("something") != 0) // works fine
x = generic_map["something"].something();
// generic class - ptr_map example
typedef ptr_map<string, specialization> generic_ptr_map_t;
generic_ptr_map_t generic_ptr_map;
generic_ptr_map["something"] = * new specialization(3);
// don't do this:
generic_ptr_map_t::iterator pi;
pi = generic_ptr_map.find("something");
if(pi != generic_ptr_map.end()) {
// specialization s = i->second; // error: cannot convert from 'generic<Data>' to 'generic<Data>'. Huh?
}
// do this instead:
if(generic_map.count("something") != 0) // works fine
x = generic_ptr_map["something"].something();
}
ptr_map Replacement
ptr_map<Key, Value> can be easily replaced by a combination of ptr_list<Value> and map<Key, Value * >,
where ptr_list<Value> owns the pointers, and map indexes them.