Suppose, if a conversion from one type another type is not available through explicit casts e.g static_cast, Would it be possible to define explicit conversion operators for it?
Edit:
I’m looking for a way to define explicit conversion operators for the following:
class SmallInt {
public:
// The Default Constructor
SmallInt(int i = 0): val(i) {
if (i < 0 || i > 255)
throw std::out_of_range("Bad SmallInt initializer");
}
// Conversion Operator
operator int() const {
return val;
}
private:
std::size_t val;
};
int main()
{
SmallInt si(100);
int i = si; // here, I want an explicit conversion.
}
For user defined types you can define a type cast operator. The syntax for the operator is
You should also know that implicit type cast operators are generally frowned upon because they might allow the compiler too much leeway and cause unexpected behavior. Instead you should define
to_someType()member functions in your class to perform the type conversion.Not sure about this, but I believe C++0x allows you to specify a type cast is
explicitto prevent implicit type conversions.