[cfe-dev] Getting the FieldDecl of a template class from a MemberExpr

Douglas Gregor dgregor at apple.com
Fri May 27 11:48:25 PDT 2011


On May 27, 2011, at 10:02 AM, Adrien Chauve wrote:

> Hi,
> 
> Using a RecursiveASTVisitor, I've been trying to rename field names against some conventions.
> 
> Let's say I would like to rename Foo::bar into Foo::m_bar in the following code:
> 
> template<typename T>
> struct Foo
> {
>     int bar;
> };
> 
> int main()
> {
>     Foo<double> foo;
>     foo.bar = 2;
> 
>     return 1;
> }
> 
> 
> In my custom visitor, I implement the following method:
> 
> bool VisitMemberExpr(MemberExpr* member)
> {
>     ValueDecl* v = member->getMemberDecl(); // FieldDecl or CXXMethodDecl
>     ...
> }
> 
> But the FieldDecl I get when visiting the statement corresponding to "foo.bar=2;" is Foo<double>::bar, but not Foo::bar.
> 
> So my question is: is it possible to get the FieldDecl of Foo<T>::bar from the FieldDecl of Foo<double>::bar ? at least when the struct is not specialized? 
> What happens when the struct is specialized?

For fields, this is a pain. You'll actually have to look at the type that owns the field (a ClassTemplateSpecializationDecl), check whether it was instantiated vs. specialized (using getSpecializationKind()) and, if it was instantiated, retrieve the class template from which is was instantiated (getSpecializedTemplate()).

Utility functions to do this well---e.g., adding a FieldDecl *FieldDecl::getInstantiatedFrom() const member---would be welcome :)

	- Doug



More information about the cfe-dev mailing list