1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
|
#include <iostream>
#include <map>
#include <algorithm>
using namespace std;
std::map<size_t, const char *> _reps{
{typeid(char).hash_code(), "char"},
{typeid(short).hash_code(), "short"},
{typeid(unsigned short).hash_code(), "unsigned short"},
{typeid(int).hash_code(), "int"},
{typeid(unsigned int).hash_code(), "unsigned"},
{typeid(long unsigned int).hash_code(), "long unsigned"},
{typeid(long long int).hash_code(), "long long"},
{typeid(long int).hash_code(), "long"},
{typeid(double).hash_code(), "double"},
{typeid(long double).hash_code(), "long double"},
{typeid(float).hash_code(), "float"},
{typeid(unsigned char).hash_code(), "unsigned char"}
};
template<typename _T>
class _TH
{
_T obj;
template<typename T>
friend ostream& operator<<(ostream& os, const _TH<T>& elem)
{
const size_t hc = typeid(T).hash_code();
if (_reps.find(hc) == _reps.end())
return os << typeid(elem.obj).name(); // ouput example: int
return os << _reps[hc]; // output example "NSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE"
}
public:
_TH(_T t): obj{t} {}
};
template<typename _T>
class _THP
{
_T obj;
template<typename T>
friend ostream& operator<<(ostream& os, const _THP<T *>& elem)
{
const size_t hc = typeid(*elem.obj).hash_code();
if (_reps.find(hc) == _reps.end())
return os << typeid(*elem.obj).name() << "*" << " (" << &elem.obj << ")"; // output example "int* (0x61fe00)"
return os << _reps[hc] << "*" << " (" << &elem.obj << ")"; // output example: "NSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE* (0x61fe00)"
}
public:
_THP(_T t): obj{t} {}
};
// copy or move
template<typename T>
_TH<T> typeof(T &&obj)
{
return _TH<T>{obj};
}
// pointers
template<typename T>
_THP<T *> typeof(T *obj)
{
return _THP<T *>{obj};
}
int main()
{
int *dptr = new int;
*dptr = 12;
string h{"Hell"};
cout << typeof(dptr);
delete dptr;
}
| |