Skip to content

Instantly share code, notes, and snippets.

@douglasdavis
Created January 17, 2018 20:39
Show Gist options
  • Save douglasdavis/3c2c393c33f2ce71bad3513a169e2420 to your computer and use it in GitHub Desktop.
Save douglasdavis/3c2c393c33f2ce71bad3513a169e2420 to your computer and use it in GitHub Desktop.
#ifndef TYPE_HPP
#define TYPE_HPP
#include <string>
#include <typeinfo>
std::string demangle(const char* name);
template <class T>
std::string type(const T& t) {
return demangle(typeid(t).name());
}
#endif
#ifdef __GNUG__
#include <cstdlib>
#include <memory>
#include <cxxabi.h>
std::string demangle(const char* name) {
int status = -4;
std::unique_ptr<char, void(*)(void*)> res {
abi::__cxa_demangle(name,nullptr,nullptr,&status),
std::free
};
return ( status == 0 ) ? res.get() : name;
}
#else
std::string demangle(const char* name) {
return name;
}
#endif
#include <iostream>
struct Base { virtual ~Base() {} };
struct Derived : public Base {};
int main() {
Base* ptr_base = new Derived();
std::cout << "Type of ptr_base : " << type(ptr_base) << std::endl;
std::cout << "Type of pointee : " << type(*ptr_base) << std::endl;
delete ptr_base;
}
@vgenty
Copy link

vgenty commented Feb 12, 2018

thanks! @hacker_news

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment