Advertisement
Guest User

Untitled

a guest
Feb 10th, 2016
50
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.88 KB | None | 0 0
  1. #include <type_traits>
  2. #include <iostream>
  3. #include <vector>
  4. #include <string>
  5. #include <iomanip>
  6.  
  7. //it's a string view, not null terminated C str
  8. struct const_str{
  9. const char* str;
  10. int size;
  11.  
  12. template<int N>
  13. constexpr const_str(const char (&src)[N]) : str(src), size(N - 1){} // -1, ignore the '\0'
  14. constexpr const_str(const char* src, int n) : str(src), size(n){}
  15.  
  16. friend constexpr bool operator<(const_str lhs, const_str rhs){
  17. return (lhs.size == 0)
  18. ? rhs.size != 0
  19. : (lhs.str[0] == rhs.str[0])
  20. ? const_str(lhs.str + 1, lhs.size - 1) < const_str(rhs.str + 1, rhs.size - 1)
  21. : lhs.str[0] < rhs.str[0];
  22. }
  23. };
  24.  
  25. std::ostream& operator<<(std::ostream& os, const_str s){
  26. os.write(s.str, s.size);
  27. return os;
  28. }
  29.  
  30.  
  31. constexpr const char* rfind(const_str s, char ch){
  32. return (s.str[s.size - 1] == ch)
  33. ? (s.str + s.size - 1)
  34. : rfind(const_str(s.str, s.size - 1), ch);
  35.  
  36. }
  37.  
  38. constexpr const_str substr(const_str s, const char* p, int n){
  39. return const_str(p, s.size - (p - s.str) - n);
  40. }
  41. constexpr const_str extract_type_id(const_str s){
  42. return substr(s, rfind(s, '=') + 2, 1);
  43. }
  44.  
  45. template<typename T>
  46. constexpr const_str type_id() {
  47. return extract_type_id(__PRETTY_FUNCTION__);
  48. }
  49.  
  50. template<typename T, typename U>
  51. struct type_less{
  52. static const bool value = type_id<T>() < type_id<U>();
  53. };
  54.  
  55. //test and sample
  56.  
  57. template<typename T, typename U>
  58. void print_compare(){
  59. auto left = type_id<T>();
  60. auto right = type_id<U>();
  61.  
  62. std::cout << std::boolalpha;
  63. std::cout << "compare " << left << " < " << right << ":\t" << type_less<T, U>::value << std::endl;;
  64. }
  65.  
  66. namespace test{
  67. template<typename T> struct test1{};
  68. }
  69.  
  70. int main(){
  71. using namespace std;
  72. cout << type_id<test::test1<std::vector<std::string>>>() << endl;
  73. print_compare<int, char>();
  74. print_compare<char, int>();
  75. print_compare<int, int>();
  76.  
  77. print_compare<int, float>();
  78. print_compare<float, double>();
  79. print_compare<std::string, double>();
  80. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement