fork download
  1. #include <iostream>
  2. #include <sstream>
  3. #include <string>
  4.  
  5. struct printable
  6. {
  7. template <typename T>
  8. printable(T const* value)
  9. : data_(value), to_string_impl_(&printable::to_string_impl<T>)
  10. {}
  11.  
  12. std::string to_string() const
  13. {
  14. return to_string_impl_(data_);
  15. }
  16.  
  17. private:
  18. void const* data_;
  19. std::string (* to_string_impl_) ( void const*);
  20.  
  21. template <typename T>
  22. static std::string to_string_impl(void const* data)
  23. {
  24. std::ostringstream oss;
  25. oss << *static_cast<T const*>(data);
  26. return oss.str();
  27. }
  28. };
  29.  
  30. int main()
  31. {
  32. int i = 42;
  33. double d = 3.14;
  34.  
  35. printable a(&i), b(&d);
  36.  
  37. std::cout << "i: " << a.to_string() << '\n';
  38. std::cout << "d: " << b.to_string() << '\n';
  39. }
Success #stdin #stdout 0s 3020KB
stdin
Standard input is empty
stdout
i: 42
d: 3.14