本文介绍了用于type_info的std :: is_convertible的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

在C ++ 11中,可以使用std :: is_convertible< A,B> 确定是否可以通过将类型A的变量隐式转换为类型B。

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

如果您实际上知道类型A和B,那么这很好用,但是我所拥有的只是type_infos。所以我要寻找的是这样的函数:

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);

是否可以在C ++中实现类似的功能?如果是,怎么办?

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

推荐答案

在便携式C ++中,您不可能做自己想做的事。

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);

在此ABI中, abi :: __ class_type_info 是从 std :: type_info all std :: type_info s派生的类型程序中的动态类型是从 std :: type_info 派生的( abi :: __ class_type_info 只是一个例子)。

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

使用此ABI,可以构建一个工具,该工具可以在给定 std的情况下(在运行时)导航任何类型的继承层次结构: :type_info 。这样,您就可以确定两个 std :: type_info 代表两种类型,它们可能是 dynamic_cast 甚至是 static_cast

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.

请注意,这样的解决方案不会考虑使用转换构造函数或转换运算符。而且即使该限制是可以接受的,我也不建议您使用此路线。这不是一个容易的项目,并且很容易出错。但这可能是您的C ++实现如何实现 dynamic_cast 的方式,因此显然并非不可能。

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.

这篇关于用于type_info的std :: is_convertible的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 09:55