检查显式转换是否成功

编程入门 行业动态 更新时间:2024-10-28 04:15:15
本文介绍了检查显式转换是否成功的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我将 double 变量转换为 void pointer :

double doub = 3; void *pointer = &doub;

如果我将void指针转换为 int double :

If I convert the void pointer to int , not to double:

int i = *((int *) pointer);

我得到: i = 0 。

如何检查转换是否成功并且返回值为0,因为原始值为0或失败?

How can I check if the cast succeed and the returned value is 0 since the original value is 0, or failed?

推荐答案

因为C ++不是动态类型语言,你不能直接用 void * dynamic_cast 和一些模板包装器:

Because C++ isn't dynamically typed language you can't do it straight with void* but you have to use dynamic_cast and some template wrapper:

struct type_base { virtual ~type_base() {} template<typename T> T *get_value() { if(type<T>* t=dynamic_cast<type<T>*>(this)) return &t->value; return 0; } }; template<typename T> struct type: type_base { T value; };

这样就可以丢失类型信息并对不同类型进行查询,如下所示: p>

This enables you to 'lose' type information and query it back for different types as follows:

type<int> v; v.value=1; type_base *p=&v; float *x=p->template get_value<float>(); // fails int *y=p->template get_value<int>(); // works

更多推荐

检查显式转换是否成功

本文发布于:2023-11-07 15:05:09,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1566773.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!