Is it safe to cast-away constness in RecursiveASTVisitors?

Hi all,

I want to implement RecursiveASTVisitor to find certain nodes in AST. This class should not modify AST, so I want to make a search method to be const:

bool MyCallSearch::FindMyCall (const clang::Stmt *rootStmt ) const {

Unfortunately, RecursiveASTVisitor methods are non-const and accept non-const pointers to AST nodes. So I wonder, is it safe to cast away constness like this ? :

bool MyCallSearch::FindMyCall (const clang::Stmt rootStmt ) const {
>(this)->TraverseStmt(const_cast<clang::Stmt *>(stmt));


It should be safe to do, as long as the new code that you add to your visitor doesn’t modify AST objects. I’ve done this in the past and haven’t run into any issues.

I wonder why const overloads are not provided in this case…

вт, 10 июл. 2018 г. в 11:23, David Tarditi <>:


You could look into ConstStmtVisitor class:

There is a little problem here that it is not a recursive visitor, but it is easy to solve. For example, look at, line 1645, CaptureFinder::Visit