[英]LLDB customize print of template class
我使用 LLDB 作为我的调试器,并希望它以自定义格式打印我的模板 class MyArray<N>
。
我阅读了 LLDB 文档,并提出了 python 脚本,可以获取MyArray<N>
的公共和私有数据成员。 但是,我不知道如何获取N
(模板参数),也不知道如何获取MyArray<N>::size()
返回的结果。
这是代码
#include <stdio.h>
#include <iostream>
template<int N>
class MyArray
{
public:
MyArray(){data = new int[N];}
~MyArray(){if (data) delete[] data;}
int size() const{ return N;}
int& operator[](size_t i) { return data[i];}
int const& operator[](size_t i) const { return data[i];}
private:
int* data = nullptr;
};
template<int N>
std::ostream& operator <<(std::ostream& os, const MyArray<N>& arr)
{
os << "N = " << arr.size() << std::endl;
os << "elements in array:" << std::endl;
for (int i = 0; i < arr.size(); i++) {
if (i > 0) os << ", ";
os << arr[i];
}
return os << std::endl;
}
int main()
{
MyArray<10> arr;
for (int i = 0; i < arr.size(); i++)
arr[i] = 10 + i;
std::cout << arr << std::endl; // Yeah, I can use this for print. but I want this during LLDB debug
return 0;
}
//// 更新:添加相应的 lldb 配置~/.lldbinit
:
command script import ~/.lldbcfg/print_my_array.py
~/.lldbcfg/print_my_array.py
:
def print_my_array(valobj, internal_dict):
#N = valobj.GetChildMemberWithName("size") # failed
N = 10
data = valobj.GetChildMemberWithName("data")
info = ''
for i in range(N):
if(i>0): info += ', '
info += str(data.GetChildAtIndex(i).GetValueAsSigned(0))
info += ')'
return info
def __lldb_init_module(debugger, internal_dict):
debugger.HandleCommand('type summary add -P MyArray<10> -F ' + __name__ + '.print_my_array')
简单的方法是将N
的值存储为 static 成员:
template<int N>
class MyArray
{
public:
static constexpr const int n = N;
};
假设MyArray
不是您的类型,您可以通过特征推断模板参数:
template <typename T>
struct get_value;
template <int N>
struct get_value<MyArray<N>> {
static constexpr const n = N;
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.