Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::is_convertible for type_info

In C++11 it is possible to determine if a variable of type A can be implicitly converted to type B by using std::is_convertible<A, B>.

This works well if you actually know the types A and B, but all I have is type_infos. So what I'm looking for is a function like this:

bool myIsConvertible(const type_info& from, const type_info& to);

Is it possible to implement something like that in C++? If so, how?

like image 522
Alexander Tobias Bockstaller Avatar asked May 08 '12 16:05

Alexander Tobias Bockstaller


1 Answers

It is not possible in portable C++ to do what you want.

It may be possible to achieve a partial answer if you restrict yourself to a given platform. For example those platforms that adhere to the Itanium ABI will have an implementation of this function:

extern "C" 
void* __dynamic_cast(const void *sub,
                     const abi::__class_type_info *src,
                     const abi::__class_type_info *dst,
                     std::ptrdiff_t src2dst_offset);

In this ABI, abi::__class_type_info is a type derived from std::type_info, and all std::type_infos in the program have a dynamic type derived from std::type_info (abi::__class_type_info being just one example).

Using this ABI it is possible to build a tool that will navigate the inheritance hierarchy of any type (at run time), given its std::type_info. And in doing so you could determine if two std::type_infos represent two types that could be dynamic_cast or even static_cast to each other.

Note that such a solution would not take into account converting among types using a converting constructor or conversion operator. And even if that restriction is acceptable, I don't recommend this route. This is not an easy project, and would be very error prone. But this is probably how your C++ implementation implements dynamic_cast, so it is obviously not impossible.

like image 185
Howard Hinnant Avatar answered Sep 27 '22 17:09

Howard Hinnant