检查显式转换是否成功 [英] Check if explicit cast succeed
本文介绍了检查显式转换是否成功的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我将 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
这篇关于检查显式转换是否成功的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文