使用 libclang 通过 extern 模板发现类模板

问题描述

给定文件 test.cpp

#include <string>

struct thing
{
    std::string foo;
};

我可以使用以下 Python 使用 libclang 解析它:

#!/usr/bin/env python3

from clang import cindex

idx = cindex.Index.create()
tu = idx.parse('test.cpp')

# Sanity check: Print any diagnostics
for diagnostic in tu.diagnostics:
    print(f'DIAGNOSTIC: {diagnostic}')

def get_all_children(node):
    yield node

    for child in node.get_children():
        yield from get_all_children(child)

def find_child(node,predicate):
    for item in get_all_children(node):
        if predicate(item):
            return item

    raise ValueError('nothing matched predicate')

# Find the thing structure
thing = find_child(tu.cursor,lambda x: x.kind == cindex.CursorKind.STRUCT_DECL and x.spelling == 'thing')

# Get the std::string field
thing_foo = find_child(thing,lambda x: x.kind == cindex.CursorKind.FIELD_DECL and x.spelling == 'foo')

print(thing_foo.type.spelling)
print(thing_foo.type.get_canonical().spelling)

此脚本将打印:

std::string
std::__cxx11::basic_string<char>

这一切都在预料之中。但是,我想要的是 basic_string 类模板的类型定义,并且尽我所能,我似乎无法找到正确的调用顺序。问题在于“规范”定义 (thing_foo.type.get_canonical()) 始终引用 extern template (bits/basic_string.tcc) 中的 extern template class basic_string<char>; 定义。在这之后,我不知道去哪里才能通过声明到basic_string<T,Traits>

这里的最终目标是询问被引用类型的问题,例如“是否有 .begin() 函数”,所以我需要实际的类模板。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)