fork(1) download
  1. #include <iostream>
  2. #include <vector>
  3.  
  4. struct item
  5. {
  6. int numItems = 0;
  7. float price = 0;
  8. double foo = 0;
  9.  
  10. item(int num, float pr, double f)
  11. {
  12. numItems = num;
  13. price = pr;
  14. foo = f;
  15. }
  16. };
  17.  
  18. template <class T>
  19. void printValues(item* vecItemPtr, T item::* targetElemPtr, int numItems)
  20. {
  21. for (int i = 0; i < numItems; i++)
  22. {
  23. std::cout << (vecItemPtr[i].*targetElemPtr) << std::endl;
  24. }
  25. }
  26.  
  27. int main()
  28. {
  29. std::vector<item> test;
  30.  
  31. item item1(10, 3.0f, 8);
  32. item item2(20, 1.0f, 4);
  33.  
  34. test.reserve(2);
  35. test.push_back(item1);
  36. test.push_back(item2);
  37.  
  38. // Say I want to print numItems,
  39. printValues(test.data(), &item::numItems, test.size());
  40.  
  41. // Say I want to print price
  42. printValues(test.data(), &item::price, test.size());
  43.  
  44. // Say I want to print foo
  45. printValues(test.data(), &item::foo, test.size());
  46. }
Success #stdin #stdout 0.01s 5276KB
stdin
Standard input is empty
stdout
10
20
3
1
8
4