Wednesday, July 20, 2011

A bit of C++ The typeid operator

In C++ typeid operator is used to determine actual derived type of an object at run time. This operator is provided for runtime type identification (RTTI) support in C++.

Here follows an example of typeid operator in action:
#include <typeinfo>
#include <iostream>
#include <string>
#include <vector>

using std::cout;
using std::endl;
using std::string;
using std::vector;

int main()
{
    string v1 = "";
    cout << "v1: " << typeid(v1).name() << endl;
    vector<int> v2();
    cout << "v2: " << typeid(v2).name() << endl;

    return 0;
}

results:
v1: Ss
v2: FSt6vectorIiSaIiEEvE

std::type_info::name() returns an implementation specific name. As you can see GCC just gives you the internal, mangled name.

In GCC you can use abi::__cxa_demangle() to get nice name.

Here is example
#include <typeinfo>
#include <iostream>
#include <vector>
#include <cxxabi.h>

using std::cout;
using std::endl;
using std::vector;

int main()
{
    vector<int> v2();

    int success;
    char *realname = abi::__cxa_demangle(typeid(v2).name(), 0, 0, &success);
    cout << "v2: " << typeid(v2).name() 
        << " nice name: " << realname << endl;
    free(realname);

    return 0;
}

Results:
v2: FSt6vectorIiSaIiEEvE nice name: std::vector<int, std::allocator<int> > ()()