How do I cast to a templated type?


In gdb, if you have a pointer to something, you can cast it before printing it.

For example, this works:

print *(int*) 0xDEADBEEF

However, how do I print a std::vector<T>? Specifically a std::vector<std::string>?

If it's std::string, I can do it with std::__cxx11::string, which whatis std::string outputs, but I can't convince gdb to like std::vector<int> (as an example). Quoting it doesn't help, as it says, No symbol "std::vector<int>" in current context.

asked on Stack Overflow Jun 5, 2019 by Justin

1 Answer


One way you can do this is by using the mangled name of the type. For example, the mangled name of std::vector<int> on current gcc and libstdc++ is _ZSt6vectorIiSaIiEE, which I found by compiling the following code on the Compiler Explorer:

#include <vector>

void foo(std::vector<int>) {}
// Mangled symbol name: _Z3fooSt6vectorIiSaIiEE
// _Z means "this is C++".
// 3foo means "identifier 3 chars long, which is `foo`"
// Strip those off and you're left with: St6vectorIiSaIiEE
// Add the _Z back: _ZSt6vectorIiSaIiEE

The mangled name of std::vector<std::string> is: _ZSt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaIS5_EE, which can be verified with whatis.

Actually performing the cast:

print *(_Z3fooSt6vectorINSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEESaIS5_EE*) 0xDEADBEEF
answered on Stack Overflow Jun 5, 2019 by Justin

User contributions licensed under CC BY-SA 3.0