fork download
  1. #include <iostream>
  2.  
  3. template <class T>
  4. class Foo {
  5. public:
  6. T val;
  7. Foo(T _v): val(_v){}
  8. friend std::ostream& operator<< (std::ostream& out, const Foo& A) {
  9. out << A.val;
  10. return out;
  11. }
  12. };
  13.  
  14. // C++ does not allow partial specialization of function templates,
  15. // so we're using a class template here.
  16.  
  17. template <typename X, typename Y, bool xLarger>
  18. struct DoPlusImpl // When x is selected
  19. {
  20. typedef Foo<X> result_type;
  21. };
  22.  
  23. template <typename X, typename Y>
  24. struct DoPlusImpl<X, Y, false> // When y is selected
  25. {
  26. typedef Foo<Y> result_type;
  27. };
  28.  
  29. template <typename X, typename Y> // Select X or Y based on their size.
  30. struct DoPlus : public DoPlusImpl<X, Y, (sizeof (X) > sizeof (Y))>
  31. {};
  32.  
  33. // Use template metafunction "DoPlus" to figure out what the type should be.
  34. // (Note no runtime check of sizes, even in nonoptimized builds!)
  35. template <class X, class Y>
  36. typename DoPlus<X, Y>::result_type operator+(const Foo<X>& A, const Foo<Y> & B) {
  37. return typename DoPlus<X, Y>::result_type
  38. (A.val + B.val);
  39. }
  40.  
  41. int main() {
  42. Foo<double> a(1.5);
  43. Foo<int> b(2);
  44. std::cout << a << std::endl;
  45. std::cout << b << std::endl;
  46. std::cout << a+b << std::endl;
  47. }
  48.  
Success #stdin #stdout 0s 2896KB
stdin
Standard input is empty
stdout
1.5
2
3.5