Sign in to follow this  

C++: auto-cast a class?

This topic is 4414 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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

This topic is 4414 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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