如何使用 type_info 进行类型转换?

发布于 2024-10-17 04:24:50 字数 388 浏览 6 评论 0原文

我存储了一个指向 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

涙—继续流 2024-10-24 04:24:50

简单来说,您无法使用 type_info 来做到这一点。另外,在您的示例中,DataType 不是类型,它是指向 type_info 类型的对象的指针。你不能用它来施放。转换需要类型,而不是指针或对象!


但是,在 C++0x 中,您可以执行此操作,

    int MyVariable = 123;

    cout << (decltype(MyVariable))3.14 << endl;

    cout << static_cast<decltype(MyVariable)>(3.14) << endl;

输出:

3
3

在线演示:http://www.ideone.com/ViM2w

Simply you cannot do that using type_info. Also, in your example DataType is not a type, it's a pointer to an object of type type_info. You cannot use it to cast. Casting requires type, not pointer or object!


In C++0x, you can do this however,

    int MyVariable = 123;

    cout << (decltype(MyVariable))3.14 << endl;

    cout << static_cast<decltype(MyVariable)>(3.14) << endl;

Output:

3
3

Online Demo: http://www.ideone.com/ViM2w

平生欢 2024-10-24 04:24:50

我认为这样的选角是不可能完成的。假设您可以在运行时执行这样的“动态”转换(不是指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.

浮华 2024-10-24 04:24:50

类型转换不是一个运行时过程,它是一个编译时过程,至少对于您要转换的类型来说是这样。。我认为这是不可能的。

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.

帥小哥 2024-10-24 04:24:50

如果您愿意使用脆弱的、特定于 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文