Can someone explain why opCast is so limited?

Steven Schveighoffer schveiguy at yahoo.com
Thu Sep 6 07:47:41 PDT 2007


Question #1: I know that because you cannot overload functions based on the 
return type, they are limited.  But casting is more of a function with type 
as the parameter.  i.e.:

cast(Type)value;

I look at Type and value as the parameters to the cast.  Why doesn't opCast 
behave like:

int opCast(int)
{
  return myIntRepresentation;
}

float opCast(float)
{
  return myFloatRepresentation;
}

Question #2:  Is there a way to cast a basic type to a struct/class?  I can 
see uses for this, such as if you wanted to change an alias to a struct. 
e.g.:

before:
alias long myType;

myType convertToMyType(long x)
{
  return cast(myType)x;
}

after, I want to have methods on myType, etc:
struct myType
{
  long _value;
}

Now convertToMyType doesn't compile, and I have to go through and change all 
the casts that I previously used.   Is there a way to make it work with the 
current implementation, or does something need to be added?  What I'm 
thinking is something like a global function:

myType opCast(myType, long value)
{
  return myType(value);
}

Until these things work, there isn't a good way to make structs truly value 
types.

-Steve 




More information about the Digitalmars-d-learn mailing list