• Advertisement
Sign in to follow this  

C++: auto-cast a class?

This topic is 4481 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
Advertisement
conversion operators I believe.

IIRC:

struct scalar{
float x;
operator float(){return(x);}
};

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
Then why not use a typedef if that's the only difference?

Share this post


Link to post
Share on other sites
Quote:
Original post by silverphyre673
As in

typedef Scalar float

??


does your Scalar class do anything else?

any member functions?

EDIT: i think you got the message!

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement