-1

I plan to templatize a container class which can be used for various data types. I currently have a big concern:

  • Will my gdb still work in the template? Can I set breakpoints, print values, print stack traces, etc in a class template as in a normal member function?
  • Where are the limits? Are there serious restrictions or weird behavior to expect?

I'm not talking about debugging the template instantiation itself and I'm also not talking about extensive metaprogramming.

I did some research on the internet, but search results are full with real template debugging and it's hard to find an answer on this (hopefully) relatively simple question.

Michael
  • 7,407
  • 8
  • 41
  • 84

2 Answers2

3

You can break with gdb on all instances of a template with using the gdb rbreak command! That makes the usage much! easier.

#include <iostream>
#include <string>

template < typename T>
T Foo(T t) { return t; }

int main()
{
    std::cout << Foo<int>(1) << std::endl;
    std::cout << Foo<std::string>("Hallo") << std::endl;
}

You can use gdb as follows:

gdb> rbreak Foo<.*>
Breakpoint 4 at 0x400cc5: file main.cpp, line 5.
int Foo<int>(int);
Breakpoint 5 at 0x400cda: file main.cpp, line 5.
std::basic_string<char, std::char_traits<char>, std::allocator<char> > Foo<std::string>(std::string);

Hope this helps!

Klaus
  • 24,205
  • 7
  • 58
  • 113
  • I do identical to this solution but get a `Function "_Z3FooIiET_S0_" not defined in "/tmp/a.cpp". Make breakpoint pending on future shared library load? (y or [n]) ` for some reason. – user202729 Mar 10 '22 at 03:33
2

Normal Class

class foo
{
private:
    int x;
public:
    foo(int n = 0):x(n) {cout<<"foo::foo(int)"<<endl;}
    ~foo() {cout<<"foo::~foo()"<<endl;}
};

To put the breakpoint, we follow as below
$gdb: b foo::foo(int)
      b foo::~foo()

=========================================================

Template class Example

template<typename T>
class bar
{
private:
    T x;
public:
    bar(T n = 0):x(n) {cout<<"bar::bar(int)"<<endl;}
    ~bar() {cout<<"bar::~bar()"<<endl;}
};

To put the breakpoint, we follow as below
$gdb: b bar<int>::bar(int)
      b foo<int>::~bar()

The only thing we need to understand is(which I guess confuted you), that when we debug template class, we can not use the break point like bar<T>::bar(). When program runs, program would instantiate the template class with a particular type as bar<int>::bar().

Apart from that, there is no difference while debugging the non-template vs template based class. Only thing we need to consider is, template bases class would be bit verbose and it takes some time to understand especially.

Mantosh Kumar
  • 5,659
  • 3
  • 24
  • 48