我正在尝试为一个包含 std::set 对象的类编写一个漂亮的打印机,我还为其提供了我自己的漂亮打印机。基本上,这就是我的 C++ 代码的样子:
#include <set>
#include <iostream>
#include <cassert>
class Foo {
public:
  int x;
  bool operator<(const Foo & rhs) const {
    return this->x < rhs.x;
  }
};
class FooContainer {
public:
  std::set<Foo> content;
};
int main(int argc, char **argv) {
  FooContainer c;
  Foo f1 {1};
  Foo f2 {2};
  c.content.insert(f1);
  c.content.insert(f2);
  assert(false); // hand over to gdb
}
我希望能够漂亮地打印“FooContainer”类的对象。所以,我想要看起来像这样的漂亮打印机:
class FooPrinter(object):
    def __init__(self, val):
        self.val = val
    def to_string(self):
        return "X: " + str(self.val['x'])
class FooContainerPrinter(object):
    def __init__(self, val):
        self.val = val
    def to_string(self):
        res = ""
        for foo in self.val['content']:
            res += " " + FooPrinter(foo).to_string()
        return res
但是,尝试这些,GDB 给了我一个错误:
(gdb) p c 
Python Exception <class 'TypeError'> 'gdb.Value' object is not iterable: 
$7 =
看起来 FooContainerPrinter 只能访问 std::set 的内部成员,并且不能迭代它。我真的很想避免自己遍历 std::set 后面的红黑树。有没有一个巧妙的技巧来实现这一目标?