Dorian
Dorian

Reputation: 596

How to reuse a clang AST matcher?

I'm using AST matchers from lib clang to ensures that some code is present in the body of a foo function.

So all my matchers starts like this:

auto matcher1 = functiondecl(hasname("foo"),
                 hasdescendant(...))));


auto matcher2 = functiondecl(hasname("foo"),
                 hasdescendant(...))));

I would like to deduplicate the functiondecl(hasname("foo"), hasdescendant(...) part. So for example if I want to find a constructor, I can write

auto ctor = inFoo(cxxConstructorExpr());

It seems that I could write my own matcher using AST_MATCHER_P, but I can't figure out how.

Can you show me an example of custom matcher to deduplicate the beginning of my matchers?

Upvotes: 2

Views: 255

Answers (1)

Sedenion
Sedenion

Reputation: 6123

You can simply use

template <class T> 
auto inFoo(T && f) 
{ 
  return functiondecl(hasname("foo"), hasdescendant(std::forward<T>(f))); 
}

Upvotes: 1

Related Questions