ctti.h
Go to the documentation of this file.
1/*
2 * This file is part of ArmarX.
3 *
4 * ArmarX is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License version 2 as
6 * published by the Free Software Foundation.
7 *
8 * ArmarX is distributed in the hope that it will be useful, but
9 * WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License
14 * along with this program. If not, see <http://www.gnu.org/licenses/>.
15 *
16 * @package ArmarXCore
17 * @author Christoph Pohl ( christoph dot pohl at kit dot edu )
18 * @date 24.02.22
19 * @copyright http://www.gnu.org/licenses/gpl-2.0.txt
20 * GNU General Public License
21 */
22
23// from https://bitwizeshift.github.io/posts/2021/03/09/getting-an-unmangled-type-name-at-compile-time/
24#pragma once
25
26#include <array> // std::array
27#include <string>
28#include <string_view>
29#include <utility> // std::index_sequence
30
31namespace armarx::meta
32{
33
34 template <std::size_t... Idxs>
35 constexpr auto
36 substring_as_array(std::string_view str, std::index_sequence<Idxs...>)
37 {
38 return std::array{str[Idxs]..., '\n'};
39 }
40
41 template <typename T>
42 constexpr auto
44 {
45#if defined(__clang__)
46 constexpr auto prefix = std::string_view{"[T = "};
47 constexpr auto suffix = std::string_view{"]"};
48 constexpr auto function = std::string_view{__PRETTY_FUNCTION__};
49#elif defined(__GNUC__)
50 constexpr auto prefix = std::string_view{"with T = "};
51 constexpr auto suffix = std::string_view{"]"};
52 constexpr auto function = std::string_view{__PRETTY_FUNCTION__};
53#elif defined(_MSC_VER)
54 constexpr auto prefix = std::string_view{"type_name_array<"};
55 constexpr auto suffix = std::string_view{">(void)"};
56 constexpr auto function = std::string_view{__FUNCSIG__};
57#else
58#error Unsupported compiler
59#endif
60
61 constexpr auto start = function.find(prefix) + prefix.size();
62 constexpr auto end = function.rfind(suffix);
63
64 static_assert(start < end);
65
66 constexpr auto name = function.substr(start, (end - start));
67 return substring_as_array(name, std::make_index_sequence<name.size()>{});
68 }
69
70 template <typename T>
72 {
73 static inline constexpr auto value = type_name_array<T>();
74 };
75
76 template <typename T>
77 constexpr auto
78 type_name() -> std::string_view
79 {
80 constexpr auto& value = type_name_holder<T>::value;
81 return std::string_view{value.data(), value.size()};
82 }
83
84} // namespace armarx::meta
std::string str(const T &t)
constexpr auto substring_as_array(std::string_view str, std::index_sequence< Idxs... >)
Definition ctti.h:36
constexpr auto type_name_array()
Definition ctti.h:43
constexpr auto type_name() -> std::string_view
Definition ctti.h:78
static constexpr auto value
Definition ctti.h:73