From 9cb98475b264fe87c8f5d27d682c06870d8cded5 Mon Sep 17 00:00:00 2001 From: Erik Hofman Date: Mon, 29 Mar 2021 16:08:06 +0200 Subject: [PATCH] Fix MingW and MSVC builds: return a uniform type name across platforms. --- simgear/structure/CMakeLists.txt | 1 + simgear/structure/intern.hxx | 8 +++--- simgear/structure/test_typeid.cxx | 41 +++++++++++++++++++++++++++++++ 3 files changed, 47 insertions(+), 3 deletions(-) create mode 100644 simgear/structure/test_typeid.cxx diff --git a/simgear/structure/CMakeLists.txt b/simgear/structure/CMakeLists.txt index 6f88c17b..bfcc0e9d 100644 --- a/simgear/structure/CMakeLists.txt +++ b/simgear/structure/CMakeLists.txt @@ -50,6 +50,7 @@ if(ENABLE_TESTS) add_simgear_autotest(test_expressions expression_test.cxx) add_simgear_autotest(test_shared_ptr shared_ptr_test.cpp) add_simgear_autotest(test_commands test_commands.cxx) + add_simgear_autotest(test_typeid test_typeid.cxx) endif(ENABLE_TESTS) add_boost_test(function_list diff --git a/simgear/structure/intern.hxx b/simgear/structure/intern.hxx index 3d3e1ef9..4bc6522e 100644 --- a/simgear/structure/intern.hxx +++ b/simgear/structure/intern.hxx @@ -4,7 +4,7 @@ #include #include -#if __linux__ +#ifndef _MSC_VER #include #endif @@ -15,8 +15,10 @@ namespace simgear template std::string getTypeName(void) { -#ifdef _WIN32 - std::string name = typeid(T).name(); +#ifdef _MSC_VER + const char *type = typeid(T).name(); + const char *tn = strchr(type, ' '); + std::string name = tn ? tn+1 : type; #else // __linux__ int error = 0; char *type = abi::__cxa_demangle(typeid(T).name(), 0, 0, &error); diff --git a/simgear/structure/test_typeid.cxx b/simgear/structure/test_typeid.cxx new file mode 100644 index 00000000..5c6365be --- /dev/null +++ b/simgear/structure/test_typeid.cxx @@ -0,0 +1,41 @@ +//////////////////////////////////////////////////////////////////////// +// Test harness. +//////////////////////////////////////////////////////////////////////// + +#include +#include + +#include + +#include + +#include "intern.hxx" + +class Base {}; +class Derived : public Base {}; + +struct Base2 { virtual void foo() {} }; // polymorphic +struct Derived2 : Base2 {}; + +template +std::string Type(T type) { + return simgear::getTypeName(); +} + +int main(int ac, char ** av) +{ + Derived d1; + Base& b1 = d1; + Derived2 d2; + Base2& b2 = d2; + int i; + + SG_VERIFY(Type(d1) == "Derived"); + SG_VERIFY(Type(b1) == "Base"); + SG_VERIFY(Type(d2) == "Derived2"); + SG_VERIFY(Type(b2) == "Base2"); + SG_VERIFY(Type(i) == "int"); + + std::cout << "all tests passed" << std::endl; + return 0; +}