user3165438
user3165438

Reputation: 2661

Check if explicit cast succeed

I convert a double variable to void pointer:

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

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

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

I get : i=0.

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

Upvotes: 0

Views: 1043

Answers (1)

JarkkoL
JarkkoL

Reputation: 1918

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;
};

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

Upvotes: 1

Related Questions