fork download
  1. #include <vector>
  2. #include <list>
  3. #include <type_traits>
  4. #include <iostream>
  5.  
  6. struct MyStruct
  7. {
  8. int value;
  9. MyStruct(int value = 42) : value(value) { }
  10. const int& getInt() const { return value; }
  11. };
  12.  
  13. typedef std::list<MyStruct> StructList;
  14. typedef std::vector<const MyStruct*> StructPtrVector;
  15.  
  16. template <typename ITER_TYPE>
  17. auto getIteratorInt(ITER_TYPE iter) ->
  18. typename std::enable_if< std::is_pointer<typename ITER_TYPE::value_type>::value,
  19. const int& >::type
  20. {
  21. return (*iter)->getInt();
  22. }
  23.  
  24. template <typename ITER_TYPE>
  25. auto getIteratorInt(ITER_TYPE iter) ->
  26. typename std::enable_if< ! std::is_pointer<typename ITER_TYPE::value_type>::value,
  27. const int& >::type
  28. {
  29. return iter->getInt();
  30. }
  31.  
  32.  
  33. template <typename LIST_TYPE>
  34. void PrintInts(const LIST_TYPE& intList)
  35. {
  36. for (auto iter = intList.begin(); iter != intList.end(); ++iter)
  37. std::cout << getIteratorInt(iter) << std::endl;
  38. }
  39.  
  40. int main(void)
  41. {
  42. StructList structList;
  43. StructPtrVector structPtrs;
  44. int values[5] = { 1, 4, 6, 4, 1 };
  45. for (unsigned i = 0; i < 5; ++i)
  46. {
  47. structList.push_back(values[i]);
  48. structPtrs.push_back(&structList.back());
  49. }
  50. PrintInts(structList);
  51. PrintInts(structPtrs);
  52.  
  53. return 0;
  54. }
  55.  
Success #stdin #stdout 0s 2960KB
stdin
Standard input is empty
stdout
1
4
6
4
1
1
4
6
4
1