如何使用 type_info 进行类型转换?
我存储了一个指向 type_info
对象的指针。
int MyVariable = 123;
const std::type_info* Datatype = &typeid(MyVariable);
我如何使用它来将另一个变量类型转换为该类型?我尝试了这个,但它不起作用:
std::cout << ((*Datatype)3.14) << std::endl;
使用类型转换的函数形式也不起作用:
std::cout << (*Datatype(3.14)) << std::endl;
I've stored a pointer to a type_info
object.
int MyVariable = 123;
const std::type_info* Datatype = &typeid(MyVariable);
How might I use this to typecast another variable to that type? I tried this, but it doesn't work:
std::cout << ((*Datatype)3.14) << std::endl;
Using the function form of typecasting doesn't work, either:
std::cout << (*Datatype(3.14)) << std::endl;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
简单来说,您无法使用
type_info
来做到这一点。另外,在您的示例中,DataType
不是类型,它是指向type_info
类型的对象的指针。你不能用它来施放。转换需要类型,而不是指针或对象!但是,在 C++0x 中,您可以执行此操作,
输出:
在线演示:http://www.ideone.com/ViM2w
Simply you cannot do that using
type_info
. Also, in your exampleDataType
is not a type, it's a pointer to an object of typetype_info
. You cannot use it to cast. Casting requires type, not pointer or object!In C++0x, you can do this however,
Output:
Online Demo: http://www.ideone.com/ViM2w
我认为这样的选角是不可能完成的。假设您可以在运行时执行这样的“动态”转换(不是指
dynamic_cast
)。然后,如果您使用强制转换的结果来调用函数,编译器将无法再对参数进行类型检查,并且您可能会调用实际不存在的函数调用。因此这是不可能的。
I don't think such casting can be done. Suppose you could do "dynamic" casting like this at runtime (not to mean
dynamic_cast
). Then if you used the result of the cast to call a function the compiler could no longer do type checking on the parameters and you could invoke a function call that doesn't actually exist.Therefore it's not possible for this to work.
类型转换不是一个运行时过程,它是一个编译时过程,至少对于您要转换的类型来说是这样。。我认为这是不可能的。
Typecasting isn't a run-time process, it's a compile-time process at least for the type you're casting to. I don't think it can be done.
如果您愿意使用脆弱的、特定于 GCC 的逻辑,请查看 __dynamic_cast 和 __do_upcast 方法。这些大致对应于dynamic_cast<>。和 static_cast<>并可用于转换具有 std::type_info 的 void * 指针。
If you're willing to use fragile, GCC-specific logic, take a look at the __dynamic_cast and __do_upcast methods. These approximately correspond to dynamic_cast<> and static_cast<> and can be used to cast void * pointers for which you have the std::type_info.