fork download
  1. #include <iostream>
  2. #include <map>
  3.  
  4. struct Data {
  5. int numFriends = 0, numAcquaintances = 0, numDates = 0; // etc...
  6. };
  7.  
  8. void print_tabbed(std::ostream& os, const Data& d)
  9. {
  10. os << '\t' << d.numAcquaintances << " acquaintances\n";
  11. os << '\t' << d.numDates << " dates\n";
  12. os << '\t' << d.numFriends << " friends\n";
  13. }
  14.  
  15. enum Country { USA, Canada, France };
  16. enum Personality { Serious, Lazy, Funny };
  17.  
  18. class Religion {} *Islam = new Religion, *Hindu = new Religion;
  19.  
  20. class Person {
  21. private:
  22. std::map<Country, Data> countryStats;
  23. std::map<Personality, Data> personalityStats;
  24. std::map<Religion*, Data> religionStats;
  25.  
  26. // overloads
  27. std::map<Country, Data>& statsMap(const Country&) { return countryStats; }
  28. std::map<Personality, Data>& statsMap(const Personality&) { return personalityStats; }
  29. std::map<Religion*, Data>& statsMap(const Religion*) { return religionStats; }
  30.  
  31. public:
  32. template<typename T>
  33. void insert(const T& key, int Data::*dataPtr, int num)
  34. {
  35. statsMap(key)[key].*dataPtr += num;
  36. }
  37.  
  38. template<typename T>
  39. void insertData(const T& key, const Data& data) { statsMap(key)[key] = data; }
  40.  
  41. template <typename map_type>
  42. void print_map(std::ostream& os, map_type& m, bool blank_line = true)
  43. {
  44. for (auto& e : m)
  45. {
  46. os << e.first << '\n';
  47. print_tabbed(os, e.second);
  48. }
  49.  
  50. if (!m.empty() && blank_line)
  51. os << '\n';
  52. }
  53.  
  54. void showAllStats() { // for testing the results only (but only works for Country)
  55. print_map(std::cout, countryStats);
  56. print_map(std::cout, personalityStats);
  57. print_map(std::cout, religionStats, false);
  58.  
  59. std::cout << '\n';
  60. }
  61. };
  62.  
  63. int main() {
  64. Person bob, sam;
  65.  
  66. bob.insert(USA, &Data::numFriends, 10);
  67. bob.insert(Canada, &Data::numFriends, 100);
  68. bob.insert(Canada, &Data::numDates, 5);
  69. sam.insert(USA, &Data::numFriends, 30);
  70. sam.insert(USA, &Data::numAcquaintances, 50);
  71.  
  72. bob.insert (Funny, &Data::numAcquaintances, 20); // won't compile
  73. sam.insert (Islam, &Data::numAcquaintances, 35); // won't compile
  74. std::cout << "Bob:" << std::endl; bob.showAllStats(); // correct results, but only for Country
  75. std::cout << "Sam:" << std::endl; sam.showAllStats();
  76. std::cin.get();
  77. }
Success #stdin #stdout 0s 3480KB
stdin
Standard input is empty
stdout
Bob:
0
	0 acquaintances
	0 dates
	10 friends
1
	0 acquaintances
	5 dates
	100 friends

2
	20 acquaintances
	0 dates
	0 friends


Sam:
0
	50 acquaintances
	0 dates
	30 friends

0x96b1008
	35 acquaintances
	0 dates
	0 friends