1 /*
2 pybind11/detail/typeid.h: Compiler-independent access to type identifiers
4 Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
6 All rights reserved. Use of this source code is governed by a
7 BSD-style license that can be found in the LICENSE file.
8 */
10 #pragma once
12 #include <cstdio>
13 #include <cstdlib>
15 #if defined(__GNUG__)
16 #include <cxxabi.h>
17 #endif
19 NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
20 NAMESPACE_BEGIN(detail)
21 /// Erase all occurrences of a substring
22 inline void erase_all(std::string &string, const std::string &search) {
23 for (size_t pos = 0;;) {
24 pos = string.find(search, pos);
25 if (pos == std::string::npos) break;
26 string.erase(pos, search.length());
27 }
28 }
30 PYBIND11_NOINLINE inline void clean_type_id(std::string &name) {
31 #if defined(__GNUG__)
32 int status = 0;
33 std::unique_ptr<char, void (*)(void *)> res {
34 abi::__cxa_demangle(name.c_str(), nullptr, nullptr, &status), std::free };
35 if (status == 0)
36 name = res.get();
37 #else
38 detail::erase_all(name, "class ");
39 detail::erase_all(name, "struct ");
40 detail::erase_all(name, "enum ");
41 #endif
42 detail::erase_all(name, "pybind11::");
43 }
44 NAMESPACE_END(detail)
46 /// Return a string representation of a C++ type
47 template <typename T> static std::string type_id() {
48 std::string name(typeid(T).name());
49 detail::clean_type_id(name);
50 return name;
51 }
53 NAMESPACE_END(PYBIND11_NAMESPACE)