Skip to content

Instantly share code, notes, and snippets.

@cjxgm
Created June 21, 2018 15:47
Show Gist options
  • Save cjxgm/1c379ee20eaca81f73689786a53154c4 to your computer and use it in GitHub Desktop.
Save cjxgm/1c379ee20eaca81f73689786a53154c4 to your computer and use it in GitHub Desktop.
Getting typeid of C++ templates
#include <typeinfo>
#include <iostream>
template <template <class...> class T>
auto& template_id()
{
struct id {};
return typeid(id);
}
template <template <class...> class T, class... Args>
auto& template_id(T<Args...>*)
{
return template_id<T>();
}
template <class T>
auto& template_id()
{
return template_id((T*) nullptr);
}
template <template <int...> class T>
auto& template_id()
{
struct id {};
return typeid(id);
}
template <template <class, int> class T>
auto& template_id()
{
struct id {};
return typeid(id);
}
template <int n>
struct Foo
{
enum { foo = n };
};
namespace hello
{
template <class T>
struct Bar
{
enum : T { foo = 20 };
};
}
using namespace hello;
template <class T, int n>
struct Qux
{
enum: T { foo = n };
};
using int_bar = Bar<int>;
int main()
{
auto& foo_ti = template_id<Foo>();
auto& bar_ti = template_id<Bar>();
auto& int_bar_ti = template_id<int_bar>();
auto& int_bar_i = typeid(int_bar);
auto& qux_ti = template_id<Qux>();
std::cerr << foo_ti.name() << "\n"; // Z11template_idI3FooERDavE2id
std::cerr << bar_ti.name() << "\n"; // Z11template_idIN5hello3BarEERDavE2id
std::cerr << int_bar_ti.name() << "\n"; // Z11template_idIN5hello3BarEERDavE2id
std::cerr << int_bar_i.name() << "\n"; // N5hello3BarIiEE
std::cerr << qux_ti.name() << "\n"; // Z11template_idI3QuxERDavE2id
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment