Skip to content

Instantly share code, notes, and snippets.

@dvalters
Created December 3, 2018 09:56
Show Gist options
  • Save dvalters/a27a4710207229621fe492419bbe032f to your computer and use it in GitHub Desktop.
Save dvalters/a27a4710207229621fe492419bbe032f to your computer and use it in GitHub Desktop.
Get the type of a variable (C++17)
// This file is a "Hello, world!" in C++ language by GCC for wandbox.
#include <iostream>
#include <cstdlib>
// https://stackoverflow.com/questions/81870/is-it-possible-to-print-a-variables-type-in-standard-c
template <class T>
constexpr
std::string_view
type_name()
{
using namespace std;
#ifdef __clang__
string_view p = __PRETTY_FUNCTION__;
return string_view(p.data() + 34, p.size() - 34 - 1);
#elif defined(__GNUC__)
string_view p = __PRETTY_FUNCTION__;
# if __cplusplus < 201402
return string_view(p.data() + 36, p.size() - 36 - 1);
# else
return string_view(p.data() + 49, p.find(';', 49) - 49);
# endif
#elif defined(_MSC_VER)
string_view p = __FUNCSIG__;
return string_view(p.data() + 84, p.size() - 84 - 7);
#endif
}
int main()
{
std::cout << "Hello, Wandbox!" << std::endl;
int (*(*foo[5])(char(*)()))[3];
std::cout << "decltype(foo) is " << type_name<decltype(foo)>() << '\n';
}
// GCC reference:
// https://gcc.gnu.org/
// C++ language references:
// https://msdn.microsoft.com/library/3bstk3k5.aspx
// http://www.cplusplus.com/
// https://isocpp.org/
// http://www.open-std.org/jtc1/sc22/wg21/
// Boost libraries references:
// http://www.boost.org/doc/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment