Re: How to create a class that casting to int explicitly only?
Tao Wang wrote:
On Jul 30, 7:46 pm, blargg <blargg....@gishpuppy.com> wrote:
In article
<e23c84a3-9bfa-4c5d-87f2-eed0cb157...@a2g2000prm.googlegroups.com>,
Tao Wang <Dancef...@gmail.com> wrote:
...
class Data{
...
public:
operator int() {...};
};
So, I can use the class like,
Data d(1234);
int a = d;
However, what I really want is that user of class Data have explicitly
cast it to int.
that is, user should write the code like:
int a = (int) d;
other than:
int a = d;
How can I make the cast to int explicitly only?
class Data{
...
public:
int to_int() {...};
};
Data d(1234);
int a = (int) d; // error
int b = d.to_int(); // OK
This is similar to what I expected, however, I don't want user to
remember the interface to_int(). What I expect is that the code:
Data d(1234);
int a = (int) d; // OK
should be correct, that is, Data can convert to int, however, I don't
want it convert implicitly.
Well, if you stop using C style casts, which you should do anyway, then
you can create for yourself a new kind of cast. Several classes do this
in the boost library. Then they just have to use your new cast. If you
use this cast for other objects though they'll find it easy to remember.
In other words, make an external function but call it something that
ends in "_cast".
In fact, you could even piggy back boost::lexical_cast if you really
wanted to. Just make an operator >> (Data & in, int & out).
Really though, this problem of yours could indicate a bad design
decision. It shouldn't be unreasonable to expect the user to know the
function call they need to make to get the int out of the object.