Advertisement
Guest User

Untitled

a guest
Mar 15th, 2019
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.87 KB | None | 0 0
  1. #include <cstddef>
  2. #include <type_traits>
  3. #include <iostream>
  4. #include <string>
  5.  
  6. template <size_t N>
  7. struct priority_tag : priority_tag<N-1> {};
  8.  
  9. template <>
  10. struct priority_tag<0> {};
  11.  
  12. template <typename T, typename = decltype(std::declval<T>().toString())>
  13. void print(T&& value, const priority_tag<2> &) {
  14. std::cout << value.toString() << "\n";
  15. }
  16.  
  17. template <typename T>
  18. void print(T&& value, const priority_tag<1> &) {
  19. std::cout << value << "\n";
  20. }
  21.  
  22. template <typename T>
  23. void print(T&& value) {
  24. print(std::forward<T>(value), priority_tag<2>{});
  25. }
  26.  
  27. struct Foo {
  28. std::string toString() { return "Foo"; }
  29. };
  30. struct Bar {
  31. /* Doesn't have tOString, but does have an operator<< we can use. */
  32. friend std::ostream &operator<<(std::ostream &os, const Bar &b) {
  33. os << "Bar";
  34. return os;
  35. }
  36. };
  37.  
  38. int main() {
  39. Foo f;
  40. Bar b;
  41.  
  42. print(f);
  43. print(b);
  44. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement