casting in generic

  • Thread starter Thread starter 3nc0d3d
  • Start date Start date
3

3nc0d3d

I have needed to cast a pointer with different types for get a value.
I have try to use generic, but there are cast exception.
For example the following method:

generic<typename T> void XClass::GetValue(T gValue)
{
int iValue=34234234;
void *vValue=&iValue;

gValue=(T)*vValue;
}

can't be used for compile error (a illegal indirection method)
modifying the method in this way:

generic<typename T> void XClass::GetValue(T gValue)
{
int iValue=34234234;
void *vValue=&iValue;

unsigned long ulValue;
ulValue=*((unsigned long*)vValue);

gValue=(T)ulValue;
}

there's a runtime error (Specified cast is not valid)

How can I to use generic for this goal?

Thanks for reply

EncOdEd
 
I have needed to cast a pointer with different types for get a value.
I have try to use generic, but there are cast exception.
For example the following method:

generic<typename T> void XClass::GetValue(T gValue)
{
int iValue=34234234;
void *vValue=&iValue;

gValue=(T)*vValue;
}

you are dereferencing a void*. that will not work, since void doesn't have a
type.
can't be used for compile error (a illegal indirection method)
modifying the method in this way:

generic<typename T> void XClass::GetValue(T gValue)
{
int iValue=34234234;
void *vValue=&iValue;

unsigned long ulValue;
ulValue=*((unsigned long*)vValue);

gValue=(T)ulValue;
}

there's a runtime error (Specified cast is not valid)

What is the type that you are working with? I.e. what is T?
another thing: if T is just a value type, then changing gValue will not have
an effect in the scope of the caller.
If all you need to do is to cast one value to another, there is no need to
use a generic class unless this is part of something larger.

Could you describe what it is you are trying to do?

--

Kind regards,
Bruno van Dooren
(e-mail address removed)
Remove only "_nos_pam"
 
What is the type that you are working with? I.e. what is T?
T is a value type.
another thing: if T is just a value type, then changing gValue will not have
an effect in the scope of the caller.

You are right, the method is this:

generic<typename T> void ConvertClass::GetValue(T% gValue)
{
int iValue=34234234;
void *vValue=&iValue;

unsigned long ulValue;
ulValue=*((unsigned long*)vValue);

gValue=(T)ulValue;
}

This method is only a example, the real method reads a file mapped in
memory that contains different value type. I could create different
methods: GetRealValue(), GetIntValue(), GetLongValue() etc.. I would
like to create only one Method like that before described;

Consider: in the method I can't use this syntax: ulValue=*((T*)vValue)
because of this error: "indirections on a generic type parameter are
not allowed", so I cast the value to a big value:

ulValue=*((unsigned long*)vValue);

than I cast to the type generic:

gValue=(T)ulValue;

Thanks for your help.

Alessandro
 
Back
Top