fork download
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. template< class T >
  6. class foo
  7. {
  8. public:
  9. T _value;
  10. foo() : _value() {}
  11.  
  12. template <class U>
  13. foo(const foo<U>& that) : _value(that.getval()) {}
  14.  
  15. // I'm sure this it can be done without this being public also;
  16. T getval() const { return _value ; };
  17.  
  18. foo(const T& that) : _value(that) {}
  19.  
  20. friend foo& operator +=(foo &lhs,const foo &rhs)
  21. {
  22. lhs._value+=rhs._value;
  23. return lhs;
  24. };
  25. friend std::ostream& operator<<(std::ostream& out, const foo& me){
  26. return out <<me._value;
  27. }
  28. };
  29.  
  30. template <typename T, typename U>
  31. const foo<T> operator +(foo<T> &lhs,const foo<U> &rhs)
  32. {
  33. foo<T> result(lhs._value+rhs._value);
  34. return result;
  35. }
  36. template <typename T>
  37. const foo<T> operator +(foo<T> &lhs,const T &rhsval)
  38. {
  39. foo<T> result(lhs._value+rhsval);
  40. return result;
  41. }
  42. template <typename T>
  43. const foo<T> operator +(const T &lhsval,foo<T> &rhs)
  44. {
  45. foo<T> result(lhsval+rhs._value);
  46. return result;
  47. }
  48.  
  49.  
  50. int main(){
  51. foo< int > f, g;
  52. foo< double > dd;
  53. cout <<f<<endl;
  54. f = f + g;
  55. cout <<f<<endl;
  56. f += 3 ;
  57. cout <<f<<endl;
  58. f = f + 5;
  59. cout <<f<<endl;
  60. f = 7 + f;
  61. cout <<f<<endl;
  62. dd=dd+f;
  63. cout <<dd<<endl;
  64. dd=f+dd;
  65. cout <<dd<<endl;
  66. dd=dd+7.3;
  67. cout <<dd<<endl;
  68. }
  69.  
Success #stdin #stdout 0s 3340KB
stdin
Standard input is empty
stdout
0
0
3
8
15
15
30
37.3