jeudi 17 août 2017

Runtime string type names in C++11 vs old compilers with C++0x (demangle)

I have an old c++ program that was written on Ubuntu 14 with "experimental" C++0x features.

In that code I used the following lines to get at runtime the type of an objects (there are a lot of templates and msgpack):

const std::type_info  &ti = typeid(something);
int status;
std::string realtype = abi::__cxa_demangle(ti.name(), 0, 0, &status);

The original code was full of:

if(type=="std::string") ...

and it worked.

Now to the question... compiling it on recent Ubuntu (g++ 5.4.0) when I have a string I get:

std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >

instead of std::string.

When getting to vectors of strings, things get even more complicated.

Obviously I could change the code, but I would like to understand if there is a better or more portable way of doing it.

Minimal working code:

#include <string>
#include <iostream>

#include "cxxabi.h"

main(){
        std::string s("test");

        const std::type_info  &ti = typeid(s);
        int status;
        std::string realtype = abi::__cxa_demangle(ti.name(), 0, 0, &status);

        std::cout << "String s is of type " << realtype << std::endl;
}

Aucun commentaire:

Enregistrer un commentaire