2

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?

Dorian
  • 490
  • 2
  • 10
  • Wouldn't `template auto inFoo(T && f) { return functiondecl(hasname("foo"), hasdescendant(std::forward(f))); }` work? – Sedenion Jun 10 '22 at 17:14
  • It seems to do the trick. If you could post it as an answer I'll accept it – Dorian Jun 13 '22 at 07:56

1 Answers1

1

You can simply use

template <class T> 
auto inFoo(T && f) 
{ 
  return functiondecl(hasname("foo"), hasdescendant(std::forward<T>(f))); 
}
Sedenion
  • 5,421
  • 2
  • 14
  • 42