get template parameter name and type with Boost demangle
Have you ever tied to get the type of a variable by its name? for instance “int” or “string“? The following code snippet shows how to use boost demangle to get the type:
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 |
#include <boost/units/detail/utility.hpp> #include <boost/shared_ptr.hpp> template <typename T> void foo(boost::shared_ptr<T> var) { std::string var_type= boost::units::detail::demangle(typeid(*var.get()).name()); if(var_type.find("int") !=std::string::npos ) { std::cout<<"Type of var is int" <<std::endl; }else if(var_type.find("float") !=std::string::npos ) { std::cout<<"Type of var is int" <<std::endl; } else { std::cout<<"Type of var is "<<var_type <<std::endl; } } int main() { boost::shared_ptr<int > x_ptr(new int ); *x_ptr=10; foo(x_ptr); boost::shared_ptr<float > y_ptr(new float ); *y_ptr=10.3; foo(y_ptr); boost::shared_ptr<double > z_ptr(new double ); *z_ptr=10.3; foo(z_ptr); return 0; } |