8

The X: Trying to write an internal clang tidy tool that finds an expression that contains two types (A, B) and then throws if const A& is implicitly convertible to B?

Given I can find two CXXRecordDecl for the classes, can I easily detect if A is implicitly convertible to B?

I've thought of walking over the constructors but that won't cover if B provides casting operators. I could walk over them both but I'm sure there are more cases that I'm missing here (like externally defined casting operators). Basically I want to detect if std::is_convertible<const B&, A>::value would return true, something every compiler has to do when validating a cast, but very difficult for a human to write...

IdeaHat
  • 7,641
  • 1
  • 22
  • 53
  • by implicit, what do you mean? – 9301293 Oct 24 '18 at 21:11
  • https://en.cppreference.com/w/cpp/language/implicit_conversion Essentially, `std::is_convertible::value` would return true. – IdeaHat Oct 25 '18 at 15:26
  • It seems to me, that if you are concerned with other ways in which `A` could be converted to `B`, though operators, and such, you are going to have to make your own `is_convertible`, which looks into the class defs for those operators. – 9301293 Oct 25 '18 at 17:47
  • 1
    While that may be true that it isn't available in a way I can use today, every implementation of the compiler *has* to do this check in order to see if a implicit conversion is possible. Writing it from scratch correctly is probably super tricky cuz c++ is wack. It isn't just class defs, i'll also have to scan for stand alone operators as well, but only those available at the call site for the implicit conversion. – IdeaHat Oct 26 '18 at 23:19
  • 1
    based on https://en.cppreference.com/w/cpp/types/is_convertible I would say that you should check for inheritance (method isDerivedFrom of `CXXRecordDecl`), cast (using conversion_begin(), conversion_end() of `CXXRecordDecl`) and constructors (using ctor_begin(), conversion_end() of `CXXRecordDecl`). Don't you think it is sufficient ? – PilouPili Oct 29 '18 at 21:21
  • isDerivedFrom only works if the Derivation has an implicit copy constructor, I think? We'd also need to go find any casting operators that have the two types. Also have to be careful about value type vs rhr vs lhr. – IdeaHat Dec 13 '18 at 00:29
  • was there ever a solution for this? – OneRaynyDay Jun 12 '20 at 06:31

0 Answers0