type_info的std :: is_convertible

Ale*_*ler 7 c++ types casting typecast-operator c++11

在C++ 11中,可以确定A类型的变量是否可以隐式转换为B类型using std::is_convertible<A, B>.

如果你真的知道类型A和B,这很有效,但我只有type_infos.所以我正在寻找的是这样的函数:

bool myIsConvertible(const type_info& from, const type_info& to);
Run Code Online (Sandbox Code Playgroud)

是否有可能在C++中实现类似的东西?如果是这样,怎么样?

How*_*ant 6

便携式C++中不可能做你想做的事.

如果您将自己局限于给定平台,可能会获得部分答案.例如,那些遵循Itanium ABI的平台将具有此功能的实现:

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);
Run Code Online (Sandbox Code Playgroud)

在这个ABI中,abi::__class_type_info是一个派生自的类型std::type_info,并且程序中的所有 std::type_info s都具有从std::type_info(abi::__class_type_info仅仅是一个示例)派生的动态类型.

使用此ABI,可以构建一个工具,该工具将导航任何类型的继承层次结构(在运行时),给定它std::type_info.在这样做的过程中,您可以确定两个std::type_infos是否代表两种类型,dynamic_cast甚至static_cast可以相互存在.

请注意,这样的解决方案不会考虑使用转换构造函数或转换运算符在类型之间进行转换.即使这个限制是可以接受的,我也不推荐这条路线.这不是一个简单的项目,而且非常容易出错.但这可能是您的C++实现的实现方式dynamic_cast,因此显然并非不可能.


Inv*_*tus 1

我想如果你知道变量的 typeid 的话就可以这样做,你总是可以使用 c++ 中的 typeid 运算符知道变量的 typeid 。

  Derived* pd = new Derived;
  Base* pb = pd;
  cout << typeid( pb ).name() << endl;   //prints "class Base *"
  cout << typeid( *pb ).name() << endl;   //prints "class Derived"
  cout << typeid( pd ).name() << endl;   //prints "class Derived *"
Run Code Online (Sandbox Code Playgroud)

然后你必须创建一个multimapor ,其中键为typeid(你想知道它是否可以转换为)和值为convertible type ids(可转换类型),就像 if 一样。在这种情况下,您可以访问地图来搜索key 您的情况下的a 是否const type_info& fromvalue映射到const type_info& to。如果是,那么您可以将 bool 返回为trueor false。但在这种情况下,您需要确保您正确地看到代码中的所有类和继承。并在此基础上决定是否进行合法转换并在此基础上添加到地图上。但这将是一个乏味的过程,而且我看不出它有任何用处。

一般来说,C++ 可以让您知道dynamic cast一个类型是否可以正确转换为其他类型。虽然static_cast甚至会相互转换不兼容的类型,并且使用不当会导致运行时错误