Skip to content

Instantly share code, notes, and snippets.

@AlexisTM
Created May 5, 2021 12:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AlexisTM/0cdaea512268a3c519ee2e167b21669d to your computer and use it in GitHub Desktop.
Save AlexisTM/0cdaea512268a3c519ee2e167b21669d to your computer and use it in GitHub Desktop.
Print types of variables at runtime c++
#include <type_name.h>
#include <iostream>
class A {
public:
int a = 1;
int b = 2;
int c = 3;
};
int main() {
A test{};
A& test_ref = test;
A* test_ptr = &test;
auto auto_ref = test_ref;
const auto& auto_ref2 = test_ref;
auto& auto_ref3 = test;
std::cout << type_name<decltype(test)>() << std::endl;
std::cout << type_name<decltype(test_ptr)>() << std::endl;
std::cout << type_name<decltype(test_ref)>() << std::endl;
std::cout << type_name<decltype(auto_ref)>() << std::endl;
std::cout << type_name<decltype(auto_ref2)>() << std::endl;
std::cout << type_name<decltype(auto_ref3)>() << std::endl;
}
#include <memory>
#include <string>
#include <cxxabi.h>
template <class T>
std::string
type_name()
{
typedef typename std::remove_reference<T>::type TR;
std::unique_ptr<char, void(*)(void*)> own
(
#ifndef _MSC_VER
abi::__cxa_demangle(typeid(TR).name(), nullptr,
nullptr, nullptr),
#else
nullptr,
#endif
std::free
);
std::string r = own != nullptr ? own.get() : typeid(TR).name();
if (std::is_const<TR>::value)
r += " const";
if (std::is_volatile<TR>::value)
r += " volatile";
if (std::is_lvalue_reference<T>::value)
r += "&";
else if (std::is_rvalue_reference<T>::value)
r += "&&";
return r;
}
@AlexisTM
Copy link
Author

AlexisTM commented May 5, 2021

https://godbolt.org/z/W4aYTf4Pe

Result:

A*
A&
A
A const&
A&

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