I would like to derive classes from an ABC, the main difference between the children would be the key (a nested class in the ABC) to access data stored into a std::map member. Here is some test-code with comments showing the problems I encounter.
I hope the code makes it clear. I would also have methods summing all the elements of a map and that kind of things. I did not include them in the code to simplify.Code:#include <map> class Base { public: class Key { public: /* virtual bool operator<(const Key&) const = 0; NOT POSSIBLE */ }; std::map<Key, double> map; /* virtual double lookup(Key&) = 0; REMAINS PURE VIRTUAL */ }; /* THIS ONE IS CALLED */ #include <cassert> inline bool operator<(const Base::Key& lhs, const Base::Key& rhs) { assert(false); return true; } class A: public Base { public: class Key: public Base::Key { public: Key(int i = 0): i_(i) {} bool operator<(const Key& rhs) const { return i_ < rhs.i_; } private: int i_; friend bool operator<(const A::Key&, const A::Key&); }; double lookup(Key& key) { return map[key]; } }; /* NEVER CALLED */ inline bool operator<(const A::Key& lhs, const A::Key& rhs) { return lhs.i_ < rhs.i_; } int main() { A a; A::Key k1(1); A::Key k2(2); a.map[k1] = 0.1; a.map[k2] = 0.2; return 0; };
I understand that one problem comes from std::map<Key, double> where Key is not a pointer, that is probably why the operator< for the base is called, but it would be less than practical to have a std::map<Key*, double, cmp_pointees<Key> > type. I also tried this approach without much success anyway. Is there a practical solution?



LinkBack URL
About LinkBacks



CornedBee