Sign in to follow this  
silverphyre673

C++: auto-cast a class?

Recommended Posts

silverphyre673    454
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!

Share this post


Link to post
Share on other sites
bakery2k1    712
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?

Share this post


Link to post
Share on other sites
rip-off    10976
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

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this