From fc5b59a84850691aea9f19adca75d6683abafd3f Mon Sep 17 00:00:00 2001 From: Ichthyostega Date: Sat, 2 Jan 2016 22:32:42 +0100 Subject: [PATCH] change formatting helper to exploit RTTI (!) our formatting helper for diagnostics output, which is primarily used in the unit-tests, first tries to invoke a custom string conversion. If that is not possible, it falls back to printing the demangled type name of the object in question. With just a minor change we're able to evaluate RTTI here and print the actual type name, instead of the static supertype the compiler sees on invocation. We just rely on the typeid(obj) built-in function. The only catch is we have to strip the " const*" suffix (and no, it is not possible to do that on metaprogramming level, due to the special situation where we have a void*) This also prompted me to write some util functions for this often encountered task to check / remove a prefix or suffix Hopefully I've got those functions correct and safe.... --- src/lib/format-util.hpp | 11 +++++++++-- src/lib/util.hpp | 30 ++++++++++++++++++++++++++++++ 2 files changed, 39 insertions(+), 2 deletions(-) diff --git a/src/lib/format-util.hpp b/src/lib/format-util.hpp index 32bc9ab27..3b6e835b0 100644 --- a/src/lib/format-util.hpp +++ b/src/lib/format-util.hpp @@ -65,6 +65,8 @@ namespace util { using lib::meta::can_lexical2string; using lib::meta::can_IterForEach; using lib::Symbol; + using util::removePrefix; + using util::removeSuffix; using util::isnil; using std::string; using std::move; @@ -153,9 +155,14 @@ namespace util { /** @return a string denoting the type. */ template inline string - tyStr (const TY* =0) + tyStr (const TY* obj=0) { - return "«"+ lib::test::demangleCxx (typeid(TY).name())+"»"; + auto mangledType = obj? typeid(obj).name() + : typeid(TY).name(); + string typeName = lib::test::demangleCxx (mangledType); + removePrefix (typeName, "const "); + removeSuffix (typeName, " const*"); + return "«"+ typeName +"»"; } template diff --git a/src/lib/util.hpp b/src/lib/util.hpp index effff2312..ecef0d548 100644 --- a/src/lib/util.hpp +++ b/src/lib/util.hpp @@ -155,6 +155,36 @@ namespace util { return 0 == str.rfind(prefix, 0); } + /** check if string ends with the given suffix */ + inline bool + endsWith (string const& str, string const& suffix) + { + size_t l = suffix.length(); + if (l > str.length()) return false; + size_t pos = str.length() - l; + return pos == str.find(suffix, pos); + } + + inline bool + endsWith (string const& str, const char* suffix) + { + return endsWith (str, string(suffix)); + } + + inline void + removePrefix (string& str, string const& prefix) + { + if (not startsWith (str,prefix)) return; + str = str.substr (prefix.length()); + } + + inline void + removeSuffix (string& str, string const& suffix) + { + if (not endsWith (str,suffix)) return; + str.resize(str.length() - suffix.length()); + } + /** shortcut for containment test on a map */ template