fork download
  1. #include <iostream>
  2. #include <type_traits>
  3. #include <cstdint>
  4.  
  5. int GetId()
  6. {
  7. static int id = 0;
  8. id++;
  9. return id;
  10. }
  11.  
  12. template <class T>
  13. struct TypeId
  14. {
  15. typedef T type;
  16. static const int id;
  17. };
  18.  
  19.  
  20. template <class T>
  21. struct TypeId<T*>
  22. {
  23. typedef T* type;
  24. static const int id = -1;
  25. };
  26.  
  27.  
  28. //static
  29. template <class T>
  30. const int TypeId<T>::id = GetId();
  31.  
  32.  
  33. class A
  34. {
  35. };
  36.  
  37. class B
  38. {
  39. };
  40.  
  41.  
  42. class C
  43. {
  44. public:
  45. C()
  46. {
  47. std::cout << "id of this for C = " << TypeId<std::remove_pointer<decltype(this)>::type>::id << std::endl;
  48. }
  49. };
  50.  
  51.  
  52. template<class T>
  53. void foo(T & val)
  54. {
  55. std::cout << "foo, id of T = " << TypeId<T>::id << std::endl;
  56. }
  57.  
  58.  
  59. int main(int argc, char* argv[])
  60. {
  61. int n = 0;
  62. foo(n);
  63. int* pn = &n;
  64. foo(pn);
  65. char ch = 'a';
  66. foo(ch);
  67. char* pch = &ch;
  68. foo(pch);
  69.  
  70.  
  71. std::cout << "id of A = " << TypeId<A>::id << std::endl;
  72. std::cout << "id of C = " << TypeId<C>::id << std::endl;
  73. std::cout << "id of A = " << TypeId<A>::id << std::endl;
  74. std::cout << "id of B = " << TypeId<B>::id << std::endl;
  75. std::cout << "id of C = " << TypeId<C>::id << std::endl;
  76. std::cout << "id of int = " << TypeId<int>::id << std::endl;
  77. std::cout << "id of int32_t=" << TypeId<int32_t>::id << std::endl;
  78. std::cout << "id of int16_t=" << TypeId<int16_t>::id << std::endl;
  79. std::cout << "id of int* = " << TypeId<int*>::id << std::endl;
  80. std::cout << "id of A* = " << TypeId<A*>::id << std::endl;
  81.  
  82. return 0;
  83. }
  84.  
Success #stdin #stdout 0s 3456KB
stdin
Standard input is empty
stdout
foo, id of T = 4
foo, id of T = -1
foo, id of T = 6
foo, id of T = -1
id of A = 2
id of C = 1
id of A = 2
id of B = 3
id of C = 1
id of int = 4
id of int32_t=4
id of int16_t=5
id of int* = -1
id of A* = -1