首页 > 解决方案 > python libclang:如何区分 const 与 constexpr 类型?

问题描述

我们如何确定变量声明的类型是否是 libclang 中的 constexpr?
(以防万一,我正在使用 python 绑定)


这是一个可以玩的例子。
我无法弄清楚如何区分“const”和“constexpr”声明。

文件:a.cpp

constexpr int a = 1;
const int b = 1;

文件:test.py

import clang.cindex

def treePrint(cursor,pad=""):
    print("{}{} : {}".format(pad,cursor.kind,cursor))
    for child in cursor.get_children():
        treePrint(child,pad+"  ")

clang.cindex.Config.set_library_path("/usr/lib/llvm-6.0//lib/")
index = clang.cindex.Index.create()
translation_unit = index.parse("a.cpp", args=["-std=c++17"])

c = translation_unit.cursor
print('-- tree', '-'*60)
treePrint(c)
print('-'*70)

CursorKind = clang.cindex.CursorKind
varDecls = [x for x in c.get_children() if x.kind == CursorKind.VAR_DECL]

for vDecl in varDecls:
    print("{} : {}".format(vDecl.spelling, vDecl.type.spelling))

运行:python3 test.py
控制台输出:

-- tree ------------------------------------------------------------
CursorKind.TRANSLATION_UNIT : <clang.cindex.Cursor object at 0x7fc60e776ae8>
  CursorKind.VAR_DECL : <clang.cindex.Cursor object at 0x7fc60e776c80>
    CursorKind.INTEGER_LITERAL : <clang.cindex.Cursor object at 0x7fc60e776d90>
  CursorKind.VAR_DECL : <clang.cindex.Cursor object at 0x7fc60e776d08>
    CursorKind.INTEGER_LITERAL : <clang.cindex.Cursor object at 0x7fc60e776b70>
----------------------------------------------------------------------
a : const int
b : const int

标签: pythonc++constexprlibclang

解决方案


推荐阅读