Given two CXXRecordDecl for class A and B, is there an easy way to see if A is implicitly convertible to B?
Asked Answered
C

0

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...

Clairclairaudience answered 19/10, 2018 at 20:26 Comment(7)
by implicit, what do you mean?Importance
en.cppreference.com/w/cpp/language/implicit_conversion Essentially, std::is_convertible<const B&, A>::value would return true.Clairclairaudience
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.Importance
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.Clairclairaudience
based on 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 ?Standup
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.Clairclairaudience
was there ever a solution for this?Chromatography

© 2022 - 2024 — McMap. All rights reserved.