fork download
  1. #include <iostream>
  2. #include <string>
  3. #include <map>
  4.  
  5. template <typename T>
  6. struct GenKeyTypeOrder;
  7.  
  8.  
  9. class GenKeyImplInt {
  10. public:
  11. // true if before other Key in other
  12. virtual bool before(const GenKeyImplInt&) const = 0;
  13. // type value
  14. virtual int typeOrder() const = 0;
  15.  
  16. virtual GenKeyImplInt* clone() const = 0;
  17. virtual ~GenKeyImplInt() {}
  18.  
  19. virtual void print(std::ostream& os) const = 0;
  20. };
  21.  
  22. template <typename RealKey>
  23. class GenKeyImpl : public GenKeyImplInt {
  24. public:
  25. GenKeyImpl(RealKey realKey) : realKey(realKey) {}
  26. // true if before other Key in other
  27. virtual bool before(const GenKeyImplInt& r) const
  28. {
  29. const GenKeyImpl* rp = dynamic_cast<const GenKeyImpl*>(&r);
  30. if (rp) return realKey < rp->realKey;
  31. return typeOrder() < r.typeOrder();
  32. }
  33. // type value
  34. virtual int typeOrder() const { return GenKeyTypeOrder<RealKey>::VALUE; }
  35.  
  36. virtual GenKeyImpl* clone() const { return new GenKeyImpl(*this); }
  37. virtual void print(std::ostream& os) const { os << realKey; }
  38. private:
  39. RealKey realKey;
  40. };
  41.  
  42. class GenKey {
  43. public:
  44. // true if before other Key in other
  45. friend bool operator < (const GenKey& l, const GenKey& r)
  46. {
  47. return l.impl->before(*r.impl);
  48. }
  49. template <typename T>
  50. GenKey(T t) : impl(new GenKeyImpl<T>(t)) {}
  51. GenKey(const GenKey& oth) : impl(oth.impl->clone()) {}
  52. ~GenKey() { delete impl; }
  53. private:
  54. GenKey& operator = (const GenKey& oth); // not defined
  55. GenKeyImplInt* impl;
  56.  
  57. friend std::ostream& operator << (std::ostream& os, const GenKey& obj)
  58. {
  59. obj.impl->print(os);
  60. return os;
  61. }
  62. };
  63.  
  64.  
  65. // define for every type you want be used as generic key
  66. template <>
  67. struct GenKeyTypeOrder<int> { enum { VALUE = 0 }; };
  68. template <>
  69. struct GenKeyTypeOrder<std::string> { enum { VALUE = 1 }; };
  70.  
  71.  
  72. int main() {
  73. std::map<GenKey, int> genMap;
  74. genMap[std::string("ala")] = 7;
  75. genMap[1] = 8;
  76.  
  77. for (std::map<GenKey, int>::iterator it = genMap.begin(); it != genMap.end(); ++it)
  78. std::cout << it->first << "-->" << it->second << "\n";
  79.  
  80. }
Success #stdin #stdout 0s 3064KB
stdin
Standard input is empty
stdout
1-->8
ala-->7