fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. template <typename T>
  5. class Test {
  6. public:
  7. Test(const T &val) : m_val(val) {}
  8.  
  9. // Test<T> operator +(const Test<T> &other) {
  10. // return Test(m_val + other.m_val);
  11. // }
  12.  
  13. const T& val() const { return m_val; }
  14.  
  15. template <typename N>
  16. friend Test<N> operator +(const Test<N> &a, const Test<N> &b);
  17.  
  18. private:
  19. T m_val;
  20. };
  21.  
  22. template <typename T>
  23. Test<T> operator +(const Test<T> &a, const Test<T> &b) {
  24. return Test<T>(a.m_val + b.m_val);
  25. }
  26.  
  27. int main() {
  28. Test<int> t1(2);
  29. Test<int> t2(2);
  30. Test<int> t3 = t1 + t2;
  31.  
  32. cout << "Sum is: " << t3.val() << endl;
  33.  
  34. return 0;
  35. }
  36.  
Success #stdin #stdout 0s 3296KB
stdin
Standard input is empty
stdout
Sum is: 4