You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取类模板成员函数定义外层模板参数列表的SourceLocation?

获取类模板成员函数定义外层模板的SourceLocation

可以实现,具体步骤如下:

  1. 从你持有的对应第9行foo定义的FunctionDecl,获取它所属的FunctionTemplateDecl:

    FunctionTemplateDecl *FTD = FooDecl->getDescribedFunctionTemplate();
    if (!FTD) {
      // 当前场景下不会触发,此处仅做异常处理示例
    }
    
  2. 获取FunctionTemplateDecl的模板参数列表:

    const TemplateParameterList *TPL = FTD->getTemplateParameters();
    
  3. 第8行template<class V>的template关键字起始位置,可通过TemplateParameterList的getTemplateLoc()方法直接获取:

    SourceLocation OuterTemplateLoc = TPL->getTemplateLoc();
    

    若需要获取整个template<class V>的范围,可结合第一个模板参数的结束位置:

    SourceRange OuterTemplateRange(OuterTemplateLoc, TPL->getParam(0)->getSourceRange().getEnd());
    

说明

在Clang AST中,类模板的成员函数模板定义(即template<class V> template<class W> void my_class<V>::foo(W arg))会被合并为一个FunctionTemplateDecl,它同时包含外层类模板的参数(V)和内层成员函数模板的参数(W)。因此,这个FunctionTemplateDecl的模板参数列表的getTemplateLoc()方法,直接对应外层template<class V>的起始位置。

内容的提问来源于stack exchange,提问作者Jared Hoberock

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 02:56:00