Skip to content

Commit

Permalink
Use typeid() only if it's available
Browse files Browse the repository at this point in the history
On MSVC it is always available, otherwise it depends on whether
RTTI is enabled.
  • Loading branch information
danakj committed May 31, 2023
1 parent bd39345 commit 414cba9
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 4 deletions.
18 changes: 18 additions & 0 deletions include/fmt/core.h
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,24 @@
# endif
#endif

// Check if typeid is available.
#ifndef FMT_USE_TYPEID
// In MSVC, typeid() is available with or without RTTI.
# if defined(_MSC_VER)
# define FMT_USE_TYPEID 1
# elif defined(__RTTI) // EDG compilers.
# define FMT_USE_TYPEID 1
# elif defined(__INTEL_RTTI__) // Intel compiler.
# define FMT_USE_TYPEID 1
# elif defined(__GXX_RTTI) // G++.
# define FMT_USE_TYPEID 1
# elif FMT_HAS_FEATURE(cxx_rtti) // Clang.
# define FMT_USE_TYPEID 1
# else
# define FMT_USE_TYPEID 0
# endif
#endif

// Disable [[noreturn]] on MSVC/NVCC because of bogus unreachable code warnings.
#if FMT_EXCEPTIONS && FMT_HAS_CPP_ATTRIBUTE(noreturn) && !FMT_MSC_VERSION && \
!defined(__NVCC__)
Expand Down
12 changes: 8 additions & 4 deletions include/fmt/std.h
Original file line number Diff line number Diff line change
Expand Up @@ -274,7 +274,9 @@ struct formatter<
if (it == end || *it == '}') return it;
if (*it == 't') {
++it;
#if FMT_USE_TYPEID
with_typename_ = true;
#endif
}
return it;
}
Expand All @@ -287,8 +289,9 @@ struct formatter<
if (!with_typename_)
return detail::write_bytes(out, string_view(ex.what()), spec);

#if FMT_USE_TYPEID
const std::type_info& ti = typeid(ex);
#ifdef FMT_HAS_ABI_CXA_DEMANGLE
# ifdef FMT_HAS_ABI_CXA_DEMANGLE
int status = 0;
std::size_t size = 0;
std::unique_ptr<char, decltype(&std::free)> demangled_name_ptr(
Expand Down Expand Up @@ -327,21 +330,22 @@ struct formatter<
demangled_name_view = string_view(ti.name());
}
out = detail::write_bytes(out, demangled_name_view, spec);
#elif FMT_MSC_VERSION
# elif FMT_MSC_VERSION
string_view demangled_name_view(ti.name());
if (demangled_name_view.starts_with("class "))
demangled_name_view.remove_prefix(6);
else if (demangled_name_view.starts_with("struct "))
demangled_name_view.remove_prefix(7);
out = detail::write_bytes(out, demangled_name_view, spec);
#else
# else
out = detail::write_bytes(out, string_view(ti.name()), spec);
#endif
# endif
out = detail::write<Char>(out, Char(':'));
out = detail::write<Char>(out, Char(' '));
out = detail::write_bytes(out, string_view(ex.what()), spec);

return out;
#endif
}
};
FMT_END_NAMESPACE
Expand Down

0 comments on commit 414cba9

Please sign in to comment.