7

I use Clang to build up an AST from C++ source code and RecursiveASTVisitor to traverse the tree.

I would like to decide at a visited declaration of record if it is class, struct or union. I have an overridden function VisitCXXRecordDecl(clang::CXXRecordDecl). In this function I can check any information about CXXRecordDecl that the class offers, but I have no idea how to get thie information.

Can Anyone help me?

bmolnar
  • 171
  • 8

2 Answers2

13

Just use the isStruct, isClass, and isUnion member functions, or call getTagKind to get a TagKind value you can switch on if you prefer. They're in the TagDecl base class.

Richard Smith
  • 13,696
  • 56
  • 78
2

At runtime, C++ doesn't make a distinction between class and struct, and union is only distinguishable by the fact that its data members all share address space.

So the only way to accomplish this would be to include meta data in your class/struct/union definitions supporting the distinctions that are important to you. For example:

typedef enum { class_ct, struct_ct, union_ct } c_type;

class foo {
public:
    c_type whattype() { return class_ct; }
};

struct bar {
public:
    c_type whattype() { return struct_ct; }
};

union baz {
public:
    c_type whattype() { return union_ct; }
};

//B

Bill Weinman
  • 2,036
  • 2
  • 17
  • 12
  • 1
    From the standard: 9.5.2: "A union can have member functions (including constructors and destructors), but not virtual (10.3) functions." I have tested the above code and it works. – Bill Weinman May 08 '12 at 23:39