fork download
  1. #include <iostream>
  2. #include <tuple>
  3. #include <string>
  4. #include <cassert>
  5.  
  6. using namespace std;
  7.  
  8. struct A {
  9. A() = default;
  10. A(int v) : value_(v) {}
  11. int hash() const { return value_; }
  12.  
  13. int value_;
  14. };
  15.  
  16. struct B {
  17. B() = default;
  18. B(string v) : value_(v) {}
  19. int hash() const { return value_.size(); }
  20.  
  21. string value_;
  22. };
  23.  
  24.  
  25. template<typename T> class hash_getter {
  26. public:
  27. hash_getter(T & t): kontener_(t) {}
  28.  
  29. template<typename Y, int I> Y & get_type() { return std::get<I>(kontener_); }
  30.  
  31. int get_hash(int index) {
  32. switch (index) {
  33. case 0: return std::get<0>(kontener_).hash();
  34. case 1: return std::get<1>(kontener_).hash();
  35. default: assert(!"dupa");
  36. }
  37. }
  38.  
  39. private:
  40. T& kontener_;
  41. };
  42.  
  43. int main() {
  44. tuple<A, B> k(A(12), B("foo"));
  45.  
  46. hash_getter<decltype(k)> hasher(k);
  47.  
  48. // tutaj starczy wiedza podczas kompilacji
  49. cout << hasher.get_type<B, 1>().value_ << endl;
  50.  
  51. int index;
  52. cout << "chcesz hash ktorego obiektu?: ";
  53. cin >> index;
  54.  
  55. cout << index << " hash " << hasher.get_hash(index) << endl;
  56.  
  57. return 0;
  58. }
Success #stdin #stdout 0s 3460KB
stdin
1
stdout
foo
chcesz hash ktorego obiektu?: 1 hash 3