fork(1) download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. constexpr int n = 100;
  5.  
  6. template<typename T, T swapFor0> class SwappedValT
  7. {
  8. T tVal;
  9. public:
  10. SwappedValT() = default;
  11.  
  12. SwappedValT(T t)
  13. {
  14. if ( t == 0 ) { tVal = swapFor0; }
  15. else if( t == swapFor0 ) { tVal = 0; }
  16. else { tVal = t; }
  17. }
  18.  
  19. operator T()
  20. {
  21. if ( tVal == 0 ) { return swapFor0; }
  22. else if( tVal == swapFor0 ) { return 0; }
  23. else { return tVal; }
  24. }
  25. };
  26.  
  27. SwappedValT<int, n> arr[5];
  28.  
  29. int main()
  30. {
  31. SwappedValT<int, n> t1{0}, t2{}, t3;
  32.  
  33. cout << "zero init: " << t1
  34. << ", default init: " << t2
  35. << ", uninit: " << t3
  36. << endl;
  37.  
  38. cout << "element of array with static storage duration = " << arr[2] << endl;
  39.  
  40. // Note how SwappedValT<int, n> behaves just like int for all
  41. // practical purposes. There are limits though with operations
  42. // on references
  43. // like operator++() though which is not defined.
  44. arr[2] = 3;
  45. arr[3] = n;
  46. arr[4] = 0;
  47.  
  48. cout << "after assigning 3: " << arr[2] << endl;
  49. cout << "after assigning swap val " << n << ": " << arr[3] << endl;
  50. cout << "after assigning 0: " << arr[4] << endl;
  51. cout << "arr elem containing 3 plus 4: " << (arr[2] + 4) << endl;
  52. return 0;
  53. }
Success #stdin #stdout 0s 3096KB
stdin
Standard input is empty
stdout
zero init: 0, default init: 100, uninit: 100
element of array with static storage duration = 100
after assigning 3: 3
after assigning swap val 100: 100
after assigning 0: 0
arr elem containing 3 plus 4: 7