fork 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* targetElemPtr, int numItems)
  20. {
  21. ptrdiff_t targetElementOffset = reinterpret_cast<char*>(targetElemPtr) - reinterpret_cast<char*>(vecItemPtr);
  22.  
  23. for (int i = 0; i < numItems; i++)
  24. {
  25. std::cout << *reinterpret_cast<T*>(reinterpret_cast<char*>(vecItemPtr + i) + targetElementOffset) << std::endl;
  26. }
  27. }
  28.  
  29. int main()
  30. {
  31. std::vector<item> test;
  32.  
  33. item item1(10, 3.0f, 8);
  34. item item2(20, 1.0f, 4);
  35.  
  36. test.reserve(2);
  37. test.push_back(item1);
  38. test.push_back(item2);
  39.  
  40. // Say I want to print numItems,
  41. printValues(&test[0], &test[0].numItems, test.size());
  42.  
  43. // Say I want to print price
  44. printValues(&test[0], &test[0].price, test.size());
  45.  
  46. // Say I want to print foo
  47. printValues(&test[0], &test[0].foo, test.size());
  48. }
Success #stdin #stdout 0.01s 5452KB
stdin
Standard input is empty
stdout
10
20
3
1
8
4