How to get the template argument type from AST matcher?

Hi,

Let’s say we have code like this,

class MyClass {};
vector a;

I would like to get MyClass out as a string. We could use this matcher to get the TemplateArgument.

varDecl(hasType(classTemplateSpecializationDecl(hasTemplateArgument(0, templateArgument().bind(“TemplateType”)))))

We could also use xxx->getAsType().getAsString() to get the type string. But the thing is I can only get the type “class MyClass”. How can I get only “MyClass” without “class”?

Thanks!
Best regards,
Han

I’m not sure if this is the right way to do it, but xxx->getAsType()->getAsCXXRecordDecl()->getName() should return just the class name. It’s not generic and you have to protect yourself from getAsCXXRecordDecl returning nullptr.

Call the version of getAsString that takes a PrintingPolicy with the SuppressTagKeyword field set. Something like:

PrintingPolicy pp;
pp.SuppressTagKeyword = true;
type.getAsString(pp);

Jason

Hi Jason,

Thanks! It works. :slight_smile:

Best regards,
Han

It actually depends on what you want :slight_smile: Do you want
a) the name of the class (then what Nicola wrote is good)
b) what the user wrote as template argument; in that case, you’d want to get the TypeLoc at that point, and then use Lexer::getSourceText