Skip to content

Instantly share code, notes, and snippets.

@Innokentiy-Alaytsev
Created May 18, 2020 17:05
Show Gist options
  • Select an option

  • Save Innokentiy-Alaytsev/8e03e4693697037136721736f8b9f17d to your computer and use it in GitHub Desktop.

Select an option

Save Innokentiy-Alaytsev/8e03e4693697037136721736f8b9f17d to your computer and use it in GitHub Desktop.
Constexpr type name
#include <iostream>
#include <memory>
#include <string_view>
#if defined (__clang__) || defined (__GNUG__)
template<class TString>
constexpr auto FindTypeNameBegin (TString&& i_str) {
int index = 0;
for (auto c : i_str) {
if ('=' == c) {
index += 2;
break;
}
index++;
}
return index;
}
template<class TString>
constexpr auto FindTypeNameEnd (TString&& i_str) {
int index = 0;
for (auto c : i_str) {
if (']' == c) {
break;
}
index++;
}
return index;
}
#elif defined (_MSC_VER)
template<class TString>
constexpr auto FindTypeNameBegin (TString&& i_str) {
int index = 0;
for (auto c : i_str) {
if ('<' == c) {
index++;
break;
}
index++;
}
return index;
}
template<class TString>
constexpr auto FindTypeNameEnd (TString&& i_str) {
auto index = i_str.size () - 1;
for (auto i = i_str.size () - 1; i >= 0; --i) {
if ('>' == i_str[ i ]) {
index = i;
break;
}
}
return index;
}
#endif
template<class T>
auto constexpr TypeName () {
auto constexpr raw_name = std::string_view{
#if defined (__clang__) || defined (__GNUG__)
__PRETTY_FUNCTION__
#elif defined (_MSC_VER)
__FUNCSIG__
#endif
};
auto constexpr name_begin = FindTypeNameBegin (raw_name);
auto constexpr name_end = FindTypeNameEnd (raw_name);
return std::string_view{raw_name.data() + name_begin, name_end - name_begin};
}
template<class...>
struct S {};
constexpr auto str_v = TypeName< S<int, float, int, char, double> > ();
template<auto>
struct AS {
};
constexpr AS<str_v[0]> as{};
int main (int argc, char** argv)
{
std::cout << TypeName< int > () << '\n';
std::cout << TypeName< S<int, float, int, char, double> > () << '\n';
}
@Innokentiy-Alaytsev
Copy link
Author

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