Search code examples
c++clang-formatclang-tidy

Is there a way to enforce using "this->" for class members/methods in clang-format/clang-tidy?


I was searching everywhere, but I probably used the wrong terms. I haven't found an option for this.

The only thing I found is this unanswered question (which is however a bit broader): CPP lint: Can you enforce use of this for class variables? .


Solution

  • Given the existing options, I dont believe this is possible with clang-format, not that it will be in the future. The main reason for this is the way the program works. It doesn't parse the C++ code into and AST, instead it tokenizes the text without the need for includes (defining what it a member and what is a global variable) not a compile database (influencing defines, include paths ...) It's even possible to give it a piece of code and reformat that.

    From the nature of the problem, one could expect, If it can exist within the clang-tooling, to be a compiler warning or clang-tidy. As this should be cheap to check at compile time, a warning could be possible, although, warnings are usually about globally accepted improvements. I don't believe there a consensus on that.

    So, that leaves clang-tidy. Looking at the options, I don't see the option. I see it being possible as a readability-* check, as more controversial checks are allowed in here. Though, I think if you want this, you should write it yourself and provide it to the project.

    A final personal note: I am not convinced that this-> is a good solution, though nor is starting everything with m_ (already possible), or not doing it. It would be nice if the check would be configurable to add/remove this->, so one could try things out.