code_junkie

Print variable type in C++

Nov 10th, 2011
123
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.28 KB | None | 0 0
  1. int a = 12;
  2. cout << typeof(a) << endl;
  3.  
  4. int
  5.  
  6. cout << typeid(a).name() << endl;
  7.  
  8. #include <iostream>
  9. #include <typeinfo>
  10.  
  11. using namespace std;
  12.  
  13. int main() {
  14.  
  15. int i;
  16.  
  17. cout << typeid(i).name();
  18.  
  19. return 0;
  20. }
  21.  
  22. template <typename T> const char* typeof(T&) { return "unknown"; } // default
  23. template<> const char* typeof(int&) { return "int"; }
  24. template<> const char* typeof(float&) { return "float"; }
  25.  
  26. MyNamespace::CMyContainer<int, test_MyNamespace::CMyObject>
  27.  
  28. // MSVC 2003:
  29. class MyNamespace::CMyContainer[int,class test_MyNamespace::CMyObject]
  30. // G++ 4.2:
  31. N8MyNamespace8CMyContainerIiN13test_MyNamespace9CMyObjectEEE
  32.  
  33. #include <iostream>
  34. using namespace std;
  35.  
  36. template <typename T> class type_name {
  37. public:
  38. static const char *name;
  39. };
  40.  
  41. #define DECLARE_TYPE_NAME(x) template<> const char *type_name<x>::name = #x;
  42. #define GET_TYPE_NAME(x) (type_name<typeof(x)>::name)
  43.  
  44. DECLARE_TYPE_NAME(int);
  45.  
  46. int main()
  47. {
  48. int a = 12;
  49. cout << GET_TYPE_NAME(a) << endl;
  50. }
  51.  
  52. template <typename T> struct type_as_string;
  53.  
  54. // declare your Wibble type (probably with definition of Wibble)
  55. template <>
  56. struct type_as_string<Wibble>
  57. {
  58. static const char* const value = "Wibble";
  59. };
  60.  
  61. template <typename T>
  62. const char* get_type_as_string(const T&)
  63. {
  64. return type_as_string<T>::value;
  65. }
Add Comment
Please, Sign In to add comment