Created
May 5, 2021 12:11
-
-
Save AlexisTM/0cdaea512268a3c519ee2e167b21669d to your computer and use it in GitHub Desktop.
Print types of variables at runtime c++
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://godbolt.org/z/W4aYTf4Pe
Result: