I have a custom class that acts as an int called Integer, I would like to tell compiler how to convert certain types to Integer automatically so that I can avoid typing same thing over and over again,
someCall(Integer(1), Integer(2));
would become
someCall(1,2);
I've googled but all I could find is to do the oposite, casting Integer to int I would like to accomplish the opposite.
Write a constructor that takes int
, as:
class Integer
{
public:
Integer(int);
};
If the class Integer
has this constructor, then you can do this:
void f(Integer);
f(Integer(1)); //okay
f(1); //this is also okay!
The explanation is that when you write f(1)
, then the constructor of Integer
that takes a single argument of type int
, is automatically called and creates a temporary on the fly and and then that temporary gets passed to the function!
Now suppose you want to do exactly the opposite, that is, passing an object of type Integer
to a function takes int
:
void g(int); //NOTE: this takes int!
Integer intObj(1);
g(intObj); //passing an object of type Integer?
To make the above code work, all you need is, define a user-defined conversion function in the class as:
class Integer
{
int value;
public:
Integer(int);
operator int() { return value; } //conversion function!
};
So when you pass an object of type Integer
to a function which takes int
, then the conversion function gets invoked and the object implicity converts to int
which then passes to the function as argument. You can also do this:
int i = intObj; //implicitly converts into int
//thanks to the conversion function!
You could define constructors in Integer for those types you want to implicitly convert. Do not make them explicit
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With