Created
May 18, 2020 17:05
-
-
Save Innokentiy-Alaytsev/8e03e4693697037136721736f8b9f17d to your computer and use it in GitHub Desktop.
Constexpr type name
This file contains hidden or 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 <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'; | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://godbolt.org/z/PQjXtN