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