C++: auto-cast a class?

Started by
9 comments, last by rip-off 18 years, 5 months ago
I have a wrapper for the float type, called Scalar, which I'm using while building my physics engine. Is there any way that I could automatically cast the Scalar class into a float? For example, currently, this would give an error:

void DoSomething(float f)
{
    //some operation on f
}

void Foo
{
    Scalar x = 50.0f;
    DoSomething(x); //ERROR!  Cannot convert 'scalar' to 'float'
}
I could just do something like this: DoSomething(x.Value()); Where x.Value() returns the floating-point value of "x", but I would rather not. It doesn't look pretty [grin] If you have a better solution, please let me know. Thanks!
my siteGenius is 1% inspiration and 99% perspiration
Advertisement
conversion operators I believe.

IIRC:
struct   scalar{     float     x;     operator  float(){return(x);}};
Give your scalar class an "operator float":

class Scalar{public:operator float() const{ return value; }float value;};


Note that these implicit conversions are generally considered poor style - what does your Scalar class provide that a pure float does not?
Quote:Original post by bakery2k1
Give your scalar class an "operator float":

*** Source Snippet Removed ***

Note that these implicit conversions are generally considered poor style - what does your Scalar class provide that a pure float does not?


the ability to be changed to a double at a single point in the program,
should the need arise
Then why not use a typedef if that's the only difference?
In that case, simply use a typedef.

EDIT: Beaten!
As in

typedef Scalar float

??
my siteGenius is 1% inspiration and 99% perspiration
Other way around:
typedef float Scalar;
typedef float Scalar;
OK, OK! I don't need ten people shouting at me all at once [grin]

Thanks!
my siteGenius is 1% inspiration and 99% perspiration

This topic is closed to new replies.

Advertisement