fork download
  1. #include <string>
  2. #include <iostream>
  3.  
  4. // ----------------------------------------------
  5. // Declaring typeclass interface, no implementation
  6. // ----------------------------------------------
  7. template <typename T>
  8. class Show
  9. {
  10. public:
  11. static std::string show(T t);
  12. };
  13.  
  14. // ----------------------------------------------
  15. // Declare some instances via specification
  16. // ----------------------------------------------
  17. template <>
  18. class Show<int>
  19. {
  20. public:
  21. static std::string show(int x)
  22. {
  23. return std::to_string(x); // yep, it's c++11
  24. }
  25. };
  26.  
  27. template <>
  28. class Show<std::string>
  29. {
  30. public:
  31. static std::string show(std::string s) { return s; }
  32. };
  33.  
  34. // ----------------------------------------------
  35. // Declaring function that use generic capabilities.
  36. // Let's imagine that << is not overloaded...
  37. // ----------------------------------------------
  38. template <typename T>
  39. void print(T obj)
  40. {
  41. std::cout << Show<T>::show(obj) << std::endl;
  42. }
  43.  
  44. // ----------------------------------------------
  45. // testing
  46. // ----------------------------------------------
  47. int main()
  48. {
  49. std::string message("Hi there");
  50.  
  51. print(message);
  52. print(5);
  53. // print("Hello, world"); -- will not compile: no instance of Show
  54. return 0;
  55. }
Success #stdin #stdout 0s 3020KB
stdin
Standard input is empty
stdout
Hi there
5