William Lee
William Lee

Reputation: 337

Is there a way for GDB to print type without omitting template parameters?

It seems that for several STL containers, GDB omitts printing its template parameters. For example

(gdb) whatis a
type = std::vector<int>

And it causes problems for me.

(gdb) whatis std::vector<int>::_M_impl
No type "vector<int>" within class or namespace "std".
(gdb) p *reinterpret_cast<std::vector<int>*>(0x7fffffffd920)
A syntax error in expression, near `*>(0x7fffffffd920)'.

To get what I want, I have to manually add the not shown template parameters.

(gdb) whatis std::vector<int, std::allocator<int> >::_M_impl
type = std::_Vector_base<int, std::allocator<int> >::_Vector_impl
(gdb) p *reinterpret_cast<std::vector<int, std::allocator<int> >*>(0x7fffffffd920)
$5 = ......

However, this isn't ideal since it is hard to generic program adding these omitted template parameters. For example, given std::map<int, double>, how can I know there are extra template parameters Compare and Allocator, thus able to get std::less<Key> and std::allocator<std::pair<const Key, T> >

Is there a way for GDB to print type without omitting template parameters? Or is there another way around my problem?

Upvotes: 3

Views: 383

Answers (1)

Employed Russian
Employed Russian

Reputation: 213937

Is there a way for GDB to print type without omitting template parameters?

Use TAB-completion. Example:

$ cat t.cc
#include <map>

int main()
{
  std::map<char, int> m = {{'a', 1}, {'z', 2}};
  return 0;
}

$ g++ -g t.cc && gdb -q ./a.out
(gdb) start
Temporary breakpoint 1 at 0xa87: file t.cc, line 5.
Starting program: /tmp/a.out

Temporary breakpoint 1, main () at t.cc:5
5     std::map<char, int> m = {{'a', 1}, {'z', 2}};
(gdb) n
6     return 0;

(gdb) p 'std::map<TAB>   # Note: single quote is important here.

Completes to:

(gdb) p 'std::map<char, int, std::less<char>, std::allocator<std::pair<char const, int> > >

Now you can finish with:

(gdb) p ('std::map<char, int, std::less<char>, std::allocator<std::pair<char const, int> > >' *)&m
$1 = (std::map<char, int, std::less<char>, std::allocator<std::pair<char const, int> > > *) 0x7fffffffdb60

And finally:

(gdb) p *$1
$2 = std::map with 2 elements = {[97 'a'] = 1, [122 'z'] = 2}

Upvotes: 2

Related Questions