简体   繁体   中英

Defining your own explicit conversions

Suppose, if a conversion from one type another type is not available through explicit casts eg 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

operator <return-type>()

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 explicit to prevent implicit type conversions.

In the current standard, conversions from your type to a different type cannot be marked explicit , which make sense up to some extent: if you want to explicitly convert you can always provide a function that implements the conversion:

struct small_int {
   int value();
};
small_int si(10);
int i = si.value();   // explicit in some sense, cannot be implicitly converted

Then again, it might not make that much sense, since in the upcoming standard, if your compiler supports it, you can tag the conversion operator as explicit :

struct small_int {
   explicit operator int();
};
small_int si(10);
// int i = si;                 // error
int i = (int)si;               // ok: explicit conversion
int j = static_cast<int>(si);  // ok: explicit conversion

If this is what you want, you can define conversion operators, eg:

void foo (bool b) {}

struct S {
   operator bool () {return true;} // convert to a bool
};

int main () {
   S s;
   foo (s);  // call the operator bool.
}

Although it is not really recommended because once defined, such implicit conversion can occur in awkward places where you don't expect it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM